# cfg.py
# This file is part of qarte-5
#    
# Author: Vincent Vande Vyvre <vincent.vandevyvre@oqapy.eu>
# Copyright: 2016-2022 Vincent Vande Vyvre
# Licence: GPL3
# Home page: https://launchpad.net/qarte

import os
import json
import logging
lgg = logging.getLogger(__name__)


class Config:
    def __init__(self, core):
        self.core = core
        wspace = core.workspace['user']
        self.block_update = True
        self.cfg_file = os.path.join(wspace, 'user_config')
        if not os.path.isfile(self.cfg_file):
            self.data = self.create_config()

        else:
            self.data = self.load_config()

        self.update_config()

    def load_config(self):
        lgg.info('Load config from: %s' % self.cfg_file)
        try:
            with open(self.cfg_file, 'r') as objfile:
                cnt = objfile.read()
                return json.loads(cnt)
        except Exception as why:
            lgg.warning("Read error from: {0},".format(self.cfg_file))
            lgg.warning("reason: {0}.".format(why))
            return self.create_config()

    def create_config(self):
        """Return the default configuration.

        """
        lgg.info('Create config default')
        from data import CONFIG_DEFAULT
        return CONFIG_DEFAULT

    def update_config(self):
        if type(self.data['tv_quality']) == str:
            self.data['tv_quality'] = 720

        if not self.data['tv_quality'] in (1080, 720, 432, 360, 216):
            self.data['tv_quality'] = 720

        if not 'add_date' in self.data:
            self.data['add_date'] = False

        if not 'add_subtitle' in self.data:
            self.data['add_subtitle'] = False

        if not 'video_player' in self.data:
            self.data['video_player'] = True

        if not 'merge_files' in self.data:
            self.data['merge_files'] = True

    def save_user_config(self):
        """Save the user's preferences.

        """
        lgg.info('Save user config')
        self.data['size'] = self.core.ui.width(), self.core.ui.height()
        jsn = json.dumps(self.data, sort_keys=True, indent=4, 
                         separators=(',', ': '), ensure_ascii=False)
        try:
            with open(self.cfg_file, 'wb') as outfile:
                outfile.write(jsn.encode('utf-8', 'replace'))
                lgg.info("Configuration saved")
        except Exception as why:
            lgg.warning("Write error: {0}".format(self.cfg_file))
            lgg.warning("reason: {0}".format(why))

    def get(self, key):
        """Return the value of a configuration item.

        Args:
        key -- the name of the key
        """
        return self.data[key]

    def update(self, key, value):
        """Update the configuration.

        Args:
        key -- the name of the key
        value -- the value of the item
        """
        self.data[key] = value
        self.on_config_changed()

    def on_config_changed(self):
        """Save the config when updated.

        """
        if not self.block_update:
            self.save_config()



