import subprocess
import json
import logging

MIN_POWER = 40

def fix_zero_power(group, generilka_path="/home/i024/GENERILKA", do_pre_check=True, check_suggested_power=True):

    """
    Fix small cpu power
     - at least 40 kimkim power units
     - try gencfg power suggestor if possible
    """

    get_power_script = "./utils/common/show_power.py -g {} -t json".format(group)
    logging.debug(get_power_script)
    get_power = subprocess.Popen(
        get_power_script,
        shell=True,
        cwd=generilka_path,
        stdout=subprocess.PIPE
    )
    power = json.loads("".join(get_power.stdout.readlines()))

    instances_cpu_avg = power[group]['total']['instances_cpu_avg']

    # No need to do anything if pre-check required and power is >= 1 core
    if do_pre_check:
        if instances_cpu_avg >= MIN_POWER:
            logging.info("No need to fix zero power for %s, doing nothing", group)
            return None

    get_free_power_script = "./utils/pregen/find_most_memory_free_machines.py -s `./utils/common/show_group_hosts.py -g {}` -a show | grep ^Host | awk '{{print $4}}'".format(group)    # Ugly but working =(
#    get_free_power_script = "./utils/pregen/find_most_memory_free_machines.py -g {} -a show | grep ^Host | awk '{{print $4}}'".format(group)
    logging.debug(get_free_power_script)
    get_free_power = subprocess.Popen(
        get_free_power_script,
        shell=True,
        cwd=generilka_path,
        stdout=subprocess.PIPE
    )
    free_power_by_hosts = map(lambda x: int(float(x)), get_free_power.stdout.readlines())
    print free_power_by_hosts
    min_free_power = min(free_power_by_hosts)
    print min_free_power

    new_power = MIN_POWER
    if check_suggested_power:
        get_power_script = "./new_power_suggest.py --json {}".format(group)
        logging.debug(get_power_script)
        get_power = subprocess.Popen(
            get_power_script,
            shell=True,
            cwd=generilka_path,
            stdout=subprocess.PIPE
        )
        new_power = max(new_power, json.loads("".join(get_power.stdout.readlines()))[group])

    # Not enough cpu power on some hosts, exiting
    if instances_cpu_avg + min_free_power < new_power:
        logging.info("Not enough free cpu power to fix zero guarantee for %s, doing nothing", group)
        return None

    fix_power_script = './utils/common/fix_cpu_guarantee.py -g {} -p {}'.format(group, new_power)
    logging.info(fix_power_script)
    subprocess.Popen(
        fix_power_script,
        shell=True,
        cwd=generilka_path,
        stdout=subprocess.PIPE
    )

    return new_power

