# -*- coding: utf-8 -*-

import json
import os
from spoc.flock import locked

from . import paths

data = {}
mtime = None

def load():
    global data
    global mtime
    file_mtime = os.stat(paths.CONF_FILE).st_mtime
    if mtime != file_mtime:
        with open(paths.CONF_FILE, 'r') as f:
            data = json.load(f)
        mtime = file_mtime

def save():
    global mtime
    with open(paths.CONF_FILE, 'w') as f:
        json.dump(data, f, sort_keys=True, indent=4)
    mtime = os.stat(paths.CONF_FILE).st_mtime

@locked(paths.CONF_LOCK)
def get_apps():
    load()
    return data['apps']

@locked(paths.CONF_LOCK)
def get_common():
    load()
    return data['common']

@locked(paths.CONF_LOCK)
def get_host():
    load()
    return data['host']

@locked(paths.CONF_LOCK)
def register_app(app, definition):
    load()
    data['apps'][app] = definition
    save()

@locked(paths.CONF_LOCK)
def unregister_app(app):
    load()
    try:
        del data['apps'][app]
        save()
    except KeyError:
        pass

@locked(paths.CONF_LOCK)
def set_host(key, value):
    load()
    data['host'][key] = value
    save()

@locked(paths.CONF_LOCK)
def set_common(key, value):
    load()
    data['common'][key] = value
    save()

@locked(paths.CONF_LOCK)
def set_app(app, key, value):
    load()
    try:
        data['apps'][app][key] = value
        save()
    except KeyError:
        pass
