'''
networkTree alarms module utilities

joaoprod 2017

'''

import json

from os import path
import json


configFilePath = None
config=None

def readConfigs(filename):
    global config, configFilePath

    print filename

    filename=path.expandvars(filename)
    configFilePath = filename
    config = readJsonFile(filename)

def getSubsystemAlarmCode(subsystem):
    global config
    if config is None:
        config = readJsonFile(configFilePath)

    if subsystem in config['subsystems'].keys():
        return config['subsystems'][subsystem]['alarmCode']
    else:
        return '__'


def getAreaDetails(area):
    global config
    if config is None:
        config = readJsonFile(configFilePath)
    if area in config['areas'].keys():
        return config['areas'][area]
    else:
        print ("ERROR: Area " + area + " not found in config file.")
        return dict(name=area, order = None)

def getConfigAreas():
    global config
    if config is None:
        config = readJsonFile(configFilePath)
    return config['areas']


def updateSubsystemsConfigFile(saciPath,inputPath,outputPath):

    with open(saciPath) as file:
        saci = json.load(file)

    with open(inputPath) as file:
        config = json.load(file)

    subsystems = []
    for objects in saci.keys():
        if objects not in ['']:

            for object in saci[objects].keys():
                try:
                    subsystem = saci[objects][object]['subsystem']

                    if subsystem not in subsystems:
                        subsystems.append(subsystem)
                except:
                    print(object + " has no subsystem!")

    for subsystem in subsystems:

        if subsystem in config['subsystems'].keys():
            pass

        else:
            config['subsystems'][subsystem]=dict(alarmCode=subsystem.upper())

    with open(outputPath, 'w') as outfile:
        res = json.dump(config, outfile, sort_keys=True, indent=4, separators=(',', ': '))


def readJsonFile(filename):
    filename=path.expandvars(filename)
    if not path.isabs(filename):
        filename = path.join(path.dirname(__file__), filename)
    with open(filename) as file:
        print ("Loading "+filename+ "...")
        obj = json.load(file)
    return obj