import subprocess
import json
import logging

from update_topology import update_topology

def safe_up_topology(service, groups, generilka_path="/home/i024/GENERILKA", new_topology=None, check_log='/home/i024/service_update_log'):

    """
    Expect topology in format "stable-100-r1"
    """

    bump_is_safe = True
    bump_is_needed = False

    for group in groups:
        get_online_topology_script = "./utils/common/show_groups.py -g {} -i online_version".format(group)
        logging.info("Executing generilka script : %s", get_online_topology_script)
        get_online_topology = subprocess.Popen(
            get_online_topology_script,
            shell=True,
            cwd=generilka_path,
            stdout=subprocess.PIPE
        )
        try:
            old_topology = get_online_topology.stdout.readlines()[0].split()[1].replace("/", "-")
        except:
            bump_is_safe = False
            logging.error("Can not parse online topology for {}".format(group))
            break

        get_old_instances = subprocess.Popen("sky listinstances G@{}:{}".format(group, old_topology), shell=True, stdout=subprocess.PIPE)
        if new_topology is not None:
            get_new_instances = subprocess.Popen("sky listinstances G@{}:{}".format(group, old_topology), shell=True, stdout=subprocess.PIPE)
        else:
            get_new_instances = subprocess.Popen("sky listinstances G@{}".format(group), shell=True, stdout=subprocess.PIPE)

        old_instances = sorted(map(lambda x: x.split("@")[0], get_old_instances.stdout.readlines()))
        print "old instances: ", old_instances

        new_instances = sorted(map(lambda x: x.split("@")[0], get_new_instances.stdout.readlines()))
        print "new instances: ", new_instances

        if old_instances != new_instances:
            bump_is_safe = False
            break

        gencfg_diff_script = "export GROUP='{}'; ./tools/diffbuilder/main.py --report-type json --diff-specific-groups $GROUP -o `./utils/common/show_groups.py -g $GROUP -i online_version | sed 's/\//-/' | sed 's/tag /tag@/'` -n . | jq '.diff_result[]|[.card.power, .card.memory_per_instance]'".format(group)
        gencfg_differ = subprocess.Popen(
            gencfg_diff_script,
            shell=True,
            stdout=subprocess.PIPE,
            cwd=generilka_path
        )

        gencfg_diff_raw = gencfg_differ.stdout.readlines()
        try:
            if gencfg_diff_raw != []:
                gencfg_diff = json.loads("".join(gencfg_diff_raw))
            else:
                gencfg_diff = [None, None]
            print "gencfg diff: ", gencfg_diff

            for diffitem in gencfg_diff:
                if diffitem is not None:
                    bump_is_needed = True
                    if int(diffitem['newvalue']) < int(diffitem['oldvalue']):
                        bump_is_safe = False
                        break
        except:
            print "Gencfg differ : {}".format(gencfg_diff_script)
            print "Can't parse gencfg diff : {}".format(gencfg_diff_raw)
            bump_is_safe = False

    if bump_is_needed and bump_is_safe:
        f = open(check_log, "a")
        f.write("Updating service {}".format(service))
        return update_topology(service, new_topology)

    return None

