#!/usr/bin/python
import ujson
import sys
import os.path

from edge.path_helpers import SETUPSTORE_CONF_FILEPATH, EDGE_TYPE_SPEEDCONTROL, BASE_EDGE_JNODE_DIRPATH


def _get_id(origin, edge_id):
    return int(edge_id) - (int(origin) * 10)


def _main():
    if len(sys.argv) > 2:
        print "Wrong number of arguments"
        return 1

    requested_type = None
    if len(sys.argv) == 2:
        requested_type = sys.argv[1]

    if requested_type == 'archive':
        zbx_discovery_data = discover_archives(requested_type)

    else:
        zbx_discovery_data = discover_modules(requested_type)

    zbx_discovery_jnode = {'data': zbx_discovery_data}
    print ujson.dumps(zbx_discovery_jnode)


def discover_archives(requested_type):

    sc_dicovery = discover_modules('speedcontrol')
    zbx_discovery_data = []
    for sc in sc_dicovery:
        edge_id = int(sc['{#ORIGIN}']) * 10 + int(sc['{#ID}'])
        origin_suffix = '.%s' % str(edge_id)
        sc_conf_filepath = os.path.join(BASE_EDGE_JNODE_DIRPATH, EDGE_TYPE_SPEEDCONTROL + origin_suffix, 'main.conf')

        with open(sc_conf_filepath, 'r') as sc_conf:
            sc_conf_jnode = ujson.load(sc_conf)

        stat_path = sc_conf_jnode['services']['stat']['path']

        with open(stat_path, 'r') as stat_file:
            stat_jnode = ujson.load(stat_file)

        bs = stat_jnode['bs']

        for key, value in bs.iteritems():
            zbx_discovery_entry = {
                '{#TYPE}': requested_type,
                '{#CHANNEL}': key,
                '{#ORIGIN}': sc['{#ORIGIN}']
            }

            zbx_discovery_data.append(zbx_discovery_entry)

    return zbx_discovery_data


def discover_modules(requested_type):
    with open(SETUPSTORE_CONF_FILEPATH, 'r') as ss_conf_file:
        ss_conf_jnode = ujson.load(ss_conf_file)
    ss_groups_jnode = ss_conf_jnode['groups']

    zbx_discovery_data = []

    for group in ss_groups_jnode:

        if group['name'] == 'system':
            origin = '0'
        else:
            origin = group['name'].split('-')[-1]

        for edge_module in group['modules']:
            module_entry = os.path.abspath(edge_module).split('/')[-1]
            module_type, module_id = module_entry.split('.')

            if requested_type is not None:
                if requested_type != module_type:
                    continue

            zbx_discovery_entry = {
                '{#TYPE}': module_type,
                '{#ID}': _get_id(origin, module_id),
                '{#ORIGIN}': origin
            }

            zbx_discovery_data.append(zbx_discovery_entry)

    return zbx_discovery_data


if __name__ == '__main__':
    _main()
