import os
import logging

from guardian.system import GuardSystem, GuardSystemError
from guardian.const import CAS_PREFIX_FMT
from guardian.db import guarddb

from .env import ENV


ISO_FMT = '%Y-%m-%d_%H:%M:%S.%f'#%z'

CHANFILE_HEADER = '''
[default]
gain=1.00
datatype=4
ifoid=0
slope=1.00
acquire=3
offset=0
units=V
dcuid=4
datarate=16
'''


class GuardCtrlError(Exception):
    pass


def check_system(name):
    try:
        GuardSystem(name)
    except GuardSystemError as e:
        raise GuardCtrlError(e)


def check_vars():
    if not ENV['GUARD_CHANFILE']:
        return False
    if not ENV['IFO']:
        raise GuardCtrlError("IFO variable must be specified for writing guard channel file.")
    return True


def test_chanfile():
    if not check_vars():
        return
    CHANFILE = ENV['GUARD_CHANFILE']
    try:
        open(CHANFILE, 'a').close()
    except Exception as e:
        raise GuardCtrlError(e)


def update_global_chanfile(node_list):
    if not check_vars():
        return
    IFO = ENV['IFO']
    CHANFILE = ENV['GUARD_CHANFILE']
    logging.info("updating global channel file: {}".format(CHANFILE))
    cdir = os.path.dirname(CHANFILE)
    if not os.path.exists(cdir):
        os.makedirs(cdir)
    tfile = CHANFILE+'.new'
    with open(tfile, 'w') as f:
        # f.write(CHANFILE_HEADER.strip())
        f.write('\n\n')
        for node in node_list:
            for chan, attr in sorted(guarddb.items()):
                if not attr.get('archive'):
                    continue
                channel = CAS_PREFIX_FMT.format(IFO=IFO, SYSTEM=node) + chan
                f.write('[{}]\n'.format(channel))
    os.rename(tfile, CHANFILE)
