#!/usr/bin/python

import ujson
import sys
import os.path

from edge.webserver.sysconf import ph
from edge.webserver.sysconf.dgmod import dg
from edge.webserver.sysconf.dgconf.setupstore import SsDgconf


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


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(ph.CTRL_DGCONF_DIR, dg.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_data.append({
                '{#TYPE}': requested_type,
                '{#CHANNEL}': key,
                '{#ORIGIN}': sc['{#ORIGIN}']
            })

    return zbx_discovery_data


def discover_modules(requested_type):
    ss_dgconf = SsDgconf.load_conf()
    ss_groups_info = ss_dgconf['groups']

    zbx_discovery_data = []

    for group_info in ss_groups_info:
        group_name = group_info['name']
        if group_name == 'bs-cache':
            continue

        elif group_name == 'system':
            uimod_pid = '0'

        else:
            uimod_pid = group_name.split('-')[-1]

        for dgconf_dir in group_info['modules']:
            dgconf_name = os.path.abspath(dgconf_dir).split('/')[-1]
            dgmod_type, dgmod_id = dgconf_name.split('.')

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

            zbx_discovery_data.append({
                '{#TYPE}': dgmod_type,
                '{#ID}': _get_id(uimod_pid, dgmod_id),
                '{#ORIGIN}': uimod_pid
            })

    return zbx_discovery_data


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)


if __name__ == '__main__':
    _main()
