#!/usr/bin/python3
import copy
import json
import os

PREFERENCES_DEFAULT = \
{
    'devices': {},
    'process':
    {
        'frontend': 'emulationstation --no-exit --no-splash --vsync 0',
        'emulators': ['retroarch', 'PCSX2', 'PPSSPPSDL', 'dolphin-emu'],
    },
    'behavior':
    {
        'before frontend': '',
        'after frontend': '',
        'hold delay': 0,
        'disconnect on exit': True,
    }
}


class Database():
    def __init__(self, path):
        basename = os.path.basename(path)
        self.name = os.path.splitext(basename)[0]
        self.path = path
        if os.path.isfile(path) and os.stat(path).st_size > 0:
            self._load()
            self._validate()
        else:
            dirname = os.path.dirname(path)
            if not os.path.isdir(dirname):
                os.mkdir(dirname)
            self.db = copy.deepcopy(PREFERENCES_DEFAULT)
            with open(path, "w") as f:
                f.write(json.dumps(self.db, indent=2, sort_keys=False))
            print(f"Created preferences file for '{self.name}'")

    def _load(self):
        with open(self.path, "r") as f:
            self.db = json.load(f)
        print(f"Loaded {self.name} database")

    def _repair(self, db, default=PREFERENCES_DEFAULT):
        for key in default:
            if isinstance(default[key], dict):
                db.setdefault(key, default[key])
                self._repair(db[key], default[key])
            else:
                db.setdefault(key, default[key])
            if not isinstance(default[key], type(db[key])):
                print(f"Fixed type for '{key}': {type(key)} to {type(default[key])}")
                db[key] = default.get(key)

    def _validate(self):
        old = json.dumps(self.db, sort_keys=True)
        self._repair(self.db)
        new = json.dumps(self.db, sort_keys=True)
        if not new == old:
            print(f"Repaired missing keys in {self.name} database")
            self.save()

    def get(self, *keys):
        db = self.db
        for key in keys:
            try:
                db = db[key]
            except (TypeError, KeyError):
                print(f"Invalid query {keys} in {self.name} database")
                return None
        return db

    def save(self):
        with open(self.path, "w") as f:
            f.write(json.dumps(self.db, indent=2, sort_keys=False))
        print(f"Saved {self.name} database")
