#!/usr/bin/python

from time import localtime
import argparse
import json

from statface_client import StatfaceClient, STATFACE_PRODUCTION

from saas.tools.ssm.modules.gencfg_api import GencfgGroupRequest


import search.tools.devops.libs.utils as u


def parse_cmd_args():
    description = '''
    Indescribable nightmare
'''

    parser = argparse.ArgumentParser(description=description)

    return parser.parse_args()


def main():

    u.logger_setup(1)

    geo_range = ["SAS", "MAN", "VLA"]
    # mem_range = [5, 10, 15, 20, 25, 30, 40, 50]
    mem_range = [5, 15, 20, 25, 40, 50]
    cpu_range = range(1, 11) + [20]

    # geo_range = ["MAN"]
    # mem_range = [20]
    # cpu_range = [5]

    gencfg_client = GencfgGroupRequest()
    gencfg_client.__MAX_RETRY_COUNT = 33
    statface_client = StatfaceClient(host=STATFACE_PRODUCTION)
    report = statface_client.get_report('SAAS/resources/free_slots')

    stat_data = []

    local_date = localtime()
    year = local_date.tm_year
    month = local_date.tm_mon
    day = local_date.tm_mday

    for geo in geo_range:
        for req_memory in mem_range:
            for req_cpu in cpu_range:

                try:

                    # noindexing_nossd_slots = len(gencfg_client.collect_hosts_by_requirements("{}_SAAS_CLOUD".format(geo), req_memory, req_cpu, ssd=False, no_indexing=True))
                    noindexing_ssd_slots = len(gencfg_client.collect_hosts_by_requirements("{}_SAAS_CLOUD".format(geo), req_memory, req_cpu * 40, ssd=True, no_indexing=True))
                    # indexing_nossd_slots = len(gencfg_client.collect_hosts_by_requirements("{}_SAAS_CLOUD".format(geo), req_memory, req_cpu, ssd=False, no_indexing=False))
                    indexing_ssd_slots = len(gencfg_client.collect_hosts_by_requirements("{}_SAAS_CLOUD".format(geo), req_memory, req_cpu * 40, ssd=True, no_indexing=False))

                    collected_data = {
                        "fielddate": "{}-{}-{}".format(year, month, day),
                        "geo": geo,
                        "mem": req_memory,
                        "cpu": req_cpu,
                        # "all_slots": noindexing_nossd_slots + indexing_nossd_slots,
                        "indexing_ssd_slots": indexing_ssd_slots,
                        # "indexing_nossd_slots": indexing_nossd_slots,
                        "noindexing_ssd_slots": noindexing_ssd_slots,
                        # "noindexing_nossd_slots": noindexing_nossd_slots,
                    }
                    stat_data.append(collected_data)

                    print("Probing {}, {}Gb mem, {} cores cpu done!".format(geo, req_memory, req_cpu))

                except:
                    print("Probing {}, {}Gb mem, {} cores cpu failed!".format(geo, req_memory, req_cpu))

                print(json.dumps(stat_data, indent=2))
    report.upload_data(scale='daily', data=stat_data)


if __name__ == '__main__':
    main()
