import subprocess
import json

def check_if_topology_bump_is_safe(group, generilka_path="/home/i024/GENERILKA", old_topology=None, new_topology=None, check_log=None):

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

    if old_topology is None:
        get_online_topology = subprocess.Popen(
            "./utils/common/show_groups.py -g {} -i online_version".format(group),
            shell=True,
            cwd=generilka_path,
            stdout=subprocess.PIPE
        )
        old_topology = get_online_topology.stdout.readlines()[0].split()[1].replace("/", "-")

    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)

    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
    )

    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

    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
    except:
        print "Gencfg differ : {}".format(gencfg_diff_script)
        print "Can't parse gencfg diff : {}".format(gencfg_diff_raw)

    significant_diff_is_detected = not (old_instances == new_instances and gencfg_diff == [None, None])

#    if check_log is not None and significant_diff_is_detected:
    if check_log is not None:
        json.dump(
            {
                "group_name": group,
                "power_diff": gencfg_diff,
                "added_instances": sorted(list(set(new_instances) - set(old_instances))),
                "removed_instances": sorted(list(set(old_instances) - set(new_instances)))
            },
            check_log,
            indent=2
        )

    return not significant_diff_is_detected

