#!/usr/bin/python
# -*- coding: utf-8 -*-
### BEGIN LICENSE
# Copyright (C) 2009 Jono Bacon <jono@ubuntu.com>
# Copyright (C) 2010 Michael Budde <mbudde@gmail.com>
#
#This program is free software: you can redistribute it and/or modify it
#under the terms of the GNU General Public License version 3, as published
#by the Free Software Foundation.
#
#This program is distributed in the hope that it will be useful, but
#WITHOUT ANY WARRANTY; without even the implied warranties of
#MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
#PURPOSE.  See the GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License along
#with this program.  If not, see <http://www.gnu.org/licenses/>.
### END LICENSE


from ConfigParser import RawConfigParser
from lernid.lernidconfig import save_cache_path
from lernid.LernidOptions import Options
import logging


class Preferences(object):

    _instance = None

    def __init__(self):
        self._parser = RawConfigParser()
        self._parser.add_section('lernid')
        self._load_preferences()

    def _load_preferences(self):
        self._preferences = {
            'vertical': False,
            'show_appindicator': True,
            'main_window_maximize': False,
            'statusbar': True,
            'nick': '',
            'show_irc_time': False,
            'links_in_default_browser': False

        }
        file_name = save_cache_path('lernid')+'/config'
        try:
            config_file = open(file_name, 'r')
        except: 
            return
        self._parser.readfp(config_file)
        config_file.close()
        for item in self._parser.items('lernid'):
            if item[0] == 'width':
                if 'main_window_size' not in self._preferences:
                    self._preferences['main_window_size'] = dict()
                self._preferences['main_window_size']['width'] = int(item[1])
                continue
            if item[0] == 'height':
                if 'main_window_size' not in self._preferences:
                    self._preferences['main_window_size'] = dict()
                self._preferences['main_window_size']['height'] = int(item[1])
                continue
            if item[0] == 'hpanesmain':
                if 'hpanes' not in self._preferences:
                    self._preferences['hpanes'] = dict()
                self._preferences['hpanes']['main'] = int(item[1])
                continue
            if item[0] == 'hpanessub':
                if 'hpanes' not in self._preferences:
                    self._preferences['hpanes'] = dict()
                self._preferences['hpanes']['sub'] = int(item[1])
                continue
            if item[0] == 'vpanesmain':
                if 'vpanes' not in self._preferences:
                    self._preferences['vpanes'] = dict()
                self._preferences['vpanes']['main'] = int(item[1])
                continue
            if item[0] == 'vpanessub':
                if 'vpanes' not in self._preferences:
                    self._preferences['vpanes'] = dict()
                self._preferences['vpanes']['sub'] = int(item[1])
                continue
            if item[1].startswith('{'):        # remove old style unused options
                r = self._parser.remove_option('lernid', item[0])
                continue
            elif item[1] == "True":
                self._preferences[item[0]] = True
            elif item[1] == "False":
                self._preferences[item[0]] = False
            else:
                self._preferences[item[0]] = item[1]

    def _update(self, prefs):
        self._preferences.update(prefs)

    def _flush(self):
       for item in self._preferences:
           if item == 'hpanes':
               self._parser.set('lernid', 'hpanesmain',
                   self._preferences[item]['main'])
               self._parser.set('lernid', 'hpanessub',
                   self._preferences[item]['sub'])
           elif item == 'vpanes':
               self._parser.set('lernid', 'vpanesmain',
                   self._preferences[item]['main'])
               self._parser.set('lernid', 'vpanessub',
                   self._preferences[item]['sub'])
           elif item == 'main_window_size':
               self._parser.set('lernid', 'width',
                   self._preferences[item]['width'])
               self._parser.set('lernid', 'height',
                   self._preferences[item]['height'])
           else:
               self._parser.set('lernid', item, self._preferences[item])

       config_file = open(save_cache_path('lernid')+'/config', 'w')
       self._parser.write(config_file)
       config_file.close()

    @classmethod
    def get_instance(cls):
        if not cls._instance:
            cls._instance = cls()
        return cls._instance

    @classmethod
    def get(cls, name=None, default=None):
        """Return dict with preferences if @name is not given, else return
        the value of preference @name. If @name is not set, return @default
        which defaults to None.
        """
        klass = cls.get_instance()
        if name:
            return klass._preferences.get(name, default)
        return klass._preferences

    @classmethod
    def set(cls, *args, **kwargs):
        """set(dict) -> updates preferences with values from dict
        set(name, value) -> updates a single preference
        set(key=val, key=val, ...) -> updates preferences with key-value pairs
        """
        klass = cls.get_instance()
        if len(args) == 1:
            d = args[0]
        elif len(args) == 2:
            name, value = args
            d = {name: value}
        elif len(args) == 0 and kwargs:
            d = kwargs
        else:
            raise ValueError('set should be called as either set(key, val), '
                             'set(dict) or set(key=val, key=val, ...)')
        klass._update(d)

    @classmethod
    def flush(cls):
        klass = cls.get_instance()
        klass._flush()

if __name__ == '__main__':
    print Preferences.get('width')
    Preferences.set('width', 100)
    print Preferences.get('width')
    Preferences.set(width=200, height=300)
    print Preferences.get()
    Preferences.set({'width': 500, 'height': 200})
    print Preferences.get()
