import logging
import os 
import sys
from constants import DEFAULT_DATA_PATH
from qt import QFont

debug = logging.getLogger("settings").debug
error = logging.getLogger("settings").error
warn = logging.getLogger("settings").warn

def get_font_value(s):
    if s in ('0', 'False'): return 0
    else:                   return 1

class Settings(dict):
    def __init__(self, filename=None, path=None, autocreate=False):
        dict.__init__(self)
        self.filename = filename # settings filename
        self.path = path         # directory portion of settings file
        self.autocreate = autocreate

        self.full_path = os.path.join(path, filename) # abs path
        
        if filename:
            self.loadSettings()

    def __getitem__(self, k):
        try:
            return dict.__getitem__(self, k)
        except:
            warn("Could not locate setting %s", k)
            return ""

    def get(self, k, default=None):
        try:
            return dict.__getitem__(self, k)
        except:
            return default


    def getFilename(self):
        return self.filename


    def setFilename(self, filename):
        self.filename = filename
        self.full_path = os.path.join(self.path, self.filename)

    def getPath(self):
        return self.path

    def setPath(self, path):
        self.path = path
        self.full_path = os.path.join(self.path, self.filename)
        
    def getFullPath(self):
        return self.full_path
    

    def loadSettings(self):
        if not self.filename:
            warn("Cannot loadSettings")
            return

        if not os.access(self.full_path, os.R_OK) and self.autocreate:
            self.createInitialSettings()

        fp = None
        try:
            fp = open(self.full_path, "r")
            for line in fp:
                line = line.strip()
                if not line or line[0] == '#': continue
                name, value = line.split(':', 1)
                name = name.strip().lower()
                value = value.strip()
                dict.__setitem__(self, name, value)
            fp.close()
            debug("Loaded settings from: %s", self.full_path)
        except Exception, e:
            error(e)
        if fp: fp.close()    

    
    def saveSettings(self):
        fp = None
        err = None
        try:
            fp = open(self.full_path, "w")
            
            for k,v in self.items():
                fp.write("%s: %s\n" % (k,v))
                
        except Exception, e:
            error("Could not saveSettings: %s", e)
            err = e
        if fp: fp.close()
        return err

            
    def createInitialSettings(self):
        try:
            fp = open(self.full_path, "w")
        except Exception, e:
            error("Could not write file: %s - %s", self.full_path, str(e))
            print
            print "ReleaseForge could not create it's configuration file:", self.full_path
            print "ReleaseForge will attempt to create a configuration file if"
            print "it does not already exist.\n"
            
            print "Please refer to the ReleaseForge FAQ for more information:"
            print "      http://releaseforge.sourceforge.net/faq.html"
            sys.exit(1)          

        debug("Using %s as the data_path in %s", self.path, self.filename)
        fp.write("data_path: %s\n" % self.path)
        fp.close()
                 
        
    def parseFontStr(self, fontstr):
        # parse a font in the form: family:pt size:bold:italic:underline:strikeout
        fontstr = fontstr.strip()
        parts = fontstr.split(":")
        if len(parts) != 6: raise Exception, "Invalid font spec"


        f = QFont()
        f.setFamily(parts[0])
        f.setPointSize(int(parts[1]))
        f.setBold(get_font_value(parts[2]))
        f.setItalic(get_font_value(parts[3]))
        f.setUnderline(get_font_value(parts[4]))
        f.setStrikeOut(get_font_value(parts[5]))
        return f        

    def getFont(self, name):
        try:
            fstr = self.__getitem__(name)
            font = self.parseFontStr(fstr)
            return font
        except Exception, e:
            error(e)
            return None

    def setFont(self, name, font):
        value = "%s:%s:%s:%s:%s:%s" % (font.family(), font.pointSize(),
                                       font.bold(), font.italic(),
                                       font.underline(), font.strikeOut())
        dict.__setitem__(self, name, value)        
