import subprocess
import json
import logging

def topology_outdated(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("/", "-")
    logging.debug(old_topology)

    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)
        new_topology_expression = "tag@{}".format(new_topology)
    else:
        get_new_instances = subprocess.Popen("sky listinstances G@{}".format(group), shell=True, stdout=subprocess.PIPE)
        new_topology_expression = "."

    gencfg_diff_script = ("export GROUP='{}'; ./tools/diffbuilder/main.py --report-type json --diff-specific-groups $GROUP -o tag@{} -n {} " + \
        "| jq '.diff_result[]|[.card.power, .card.memory_per_instance]'").format(
            group,
            old_topology,
            new_topology_expression
        )
    logging.debug(gencfg_diff_script)
    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()))
    logging.info("old instances: %s", old_instances)

    new_instances = sorted(map(lambda x: x.split("@")[0], get_new_instances.stdout.readlines()))
    logging.info("new instances: %s", 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]
        logging.info("gencfg diff: %s", gencfg_diff)
    except:
        logging.error("Gencfg differ : %s", gencfg_diff_script)
        logging.error("Can't parse gencfg diff : %s", gencfg_diff_raw)

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

    added_instances = sorted(list(set(new_instances) - set(old_instances)))
    removed_instances = sorted(list(set(old_instances) - set(new_instances)))

    if check_log is not None:
        json.dump(
            {
                "group_name": group,
                "power_diff": gencfg_diff,
                "added_instances": added_instances,
                "removed_instances": removed_instances
            },
            check_log,
            indent=2
        )

    return significant_diff_is_detected, {'power_diff': gencfg_diff, "added_instances": added_instances, "removed_instances": removed_instances}

