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

from edge.path_helpers import BLOBSTORE_CONF_FILEPATH, EDGE_TYPE_SPEEDCONTROL, BASE_EDGE_JNODE_DIRPATH


def load_sc_stat():
    sc_conf_filepath = os.path.join(BASE_EDGE_JNODE_DIRPATH, EDGE_TYPE_SPEEDCONTROL + str(origin_suffix), 'main.conf')
    with open(sc_conf_filepath, 'r') as sc_conf:
        sc_conf_jnode = ujson.load(sc_conf)
    sc_stat_path = sc_conf_jnode['services']['stat']['path']
    with open(sc_stat_path, 'r') as sc_stat_file:
        sc_statistics = ujson.load(sc_stat_file)

    return sc_statistics


metric = sys.argv[1]
channel = sys.argv[2]
origin = int(sys.argv[3])
origin_suffix = '.%s' % (origin * 10)

with open(BLOBSTORE_CONF_FILEPATH, 'r') as bs_conf_file:
    bs_conf_jnode = ujson.load(bs_conf_file)

stat_path = bs_conf_jnode['monitoring']['stat-path']

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

metric_path = metric.split('.')

if metric_path[0] == 'cache':
    storages = stat_jnode['storage']
    for storage in storages:
        if storage['channel'] != channel:
            continue

        metric_path = metric.split('.')
        value = storage[metric_path[0]][metric_path[1]]

        print value
        sys.exit(0)

elif metric_path[0] == 'write':
    sc_stat = load_sc_stat()
    print sc_stat['bs'][str(channel)][metric_path[1]]

else:
    print 'Parameter not supported'
