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

import fcntl
import json

from .paths import CONF_FILE, CONF_LOCK

class Config:
    def __init__(self):
        self.load()

    def load(self):
        # Load configuration from file. Uses file lock as interprocess mutex
        with open(CONF_LOCK, 'w') as lock:
            fcntl.lockf(lock, fcntl.LOCK_EX)
            with open(CONF_FILE, 'r') as f:
                self.data = json.load(f)

    def save(self):
        # Save configuration to a file. Uses file lock as interprocess mutex
        with open(CONF_LOCK, 'w') as lock:
            fcntl.lockf(lock, fcntl.LOCK_EX)
            with open(CONF_FILE, 'w') as f:
                json.dump(self.data, f, sort_keys=True, indent=4)

    def __getitem__(self, attr):
        return self.data[attr]
