#  Copyright (C) 2004  Henning Jacobs <henning@srcco.de>
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  $Id: Preferences.py 87 2004-09-07 17:29:34Z henning $

import sys
import os.path
import types
import debug
import ConfigParser

_preffile = os.path.expanduser('~/.pycocuma')
if sys.platform == "win32":
    # Windows now uses FileClient per default:
    _config = {
      "client.connection_type":       "file",
      "client.connection_string":     os.path.expanduser("~/addressbook.vcf"),
      # Use default mailto-App from Windows-Registry:
      "client.mailto_program":        "",
      "client.url_viewer":            "",
      "client.autostart_server":      "no",
      "client.topbar":                "newContact, delContact, saveContact, SEP, duplicateContact, exportContact",
      # not used when conn_type is 'file':
      "server.addressbook_filename":  "~/addressbook.vcf",
      "server.calendar_filename":     "~/addressbook.ics",
      "server.listen_host":           "localhost",
      "server.listen_port":           "8810",
      # No logging per default:
      "server.log_filename":          ""
      }
else:
    # Use XML-RPC Server:
    _config = {
      "client.connection_type":       "xmlrpc",
      "client.connection_string":     "http://localhost:8810",
      "client.mailto_program":        "x-terminal-emulator -e pine %1",
      "client.url_viewer":            "",
      "client.autostart_server":      "yes",
      "client.topbar":                "newContact, delContact, saveContact, SEP, duplicateContact, exportContact",
      "server.addressbook_filename":  "~/addressbook.vcf",
      "server.calendar_filename":     "~/addressbook.ics",
      "server.listen_host":           "localhost",
      "server.listen_port":           "8810",
      # No logging per default:
      "server.log_filename":          ""
      }
  
def Load(filename=None):
    "Load Configuration Settings From File"
    global _preffile
    if filename: _preffile = os.path.expanduser(filename)
    cp = ConfigParser.ConfigParser()
    try:
        cp.read([_preffile])
    except:
        debug.echo("Errors while reading '"+_preffile+"'")
    for sec in cp.sections():
        name = sec.lower()
        for opt in cp.options(sec):
            _config[name + "." + opt.lower()] = unicode(cp.get(sec, opt), 'utf-8', 'replace')
                
def Save():
    "Write Configuration to File"
    cp = ConfigParser.ConfigParser()
    for key, val in zip(_config.keys(), _config.values()):
        sec, opt = key.split('.')
        if not cp.has_section(sec):
            cp.add_section(sec)
        cp.set(sec, opt, val.encode('utf-8', 'replace'))
    cp.write(open(_preffile, 'wb'))
                
def get(key, astype=None):
    "Return Configuration Option as given Type"
    # returns None if key is not set:
    ret =  _config.get(key)
    if ret is not None and astype == types.ListType:
        ret = _strToList(ret)
    return ret
    
def set(key, value):
    "Set Configuration Option"
    if type(value) == types.ListType or type(value) == types.TupleType:
        valstr = _listToStr(value)
    else:
        valstr = value
    if not isinstance(valstr, types.StringTypes):
        valstr = str(valstr)
    _config[key] = valstr
        
def has_key(key):
    "Test for Configuration Option existance"
    return _config.has_key(key)

def _listToStr(list):
    "Convert List to String for storing in Config-File"
    def escape(str):
        return str.replace('\\',r'\\').replace(',','\,')
    return ', '.join(map(escape, list))
    
def _strToList(str):
    "Convert List String from Config-File to List"
    def deescape(str):
        return str.replace('\,',',').replace(r'\\', '\\')
    # The last space char is stripped but we need it here:    
    if str[-2:] != '\,' and str[-1:] == ',':
        str = str + ' '
    ret = str.split(', ')
    i = 0
    while i<len(ret):
        # Zwei Elemente wieder zusammenfuegen, falls das Komma escaped war:
        if i+1 < len(ret) and ret[i] and ret[i][-1] == '\\'\
          and (len(ret) < 2 or ret[i][-2] != '\\'):
            ret[i] = ret[i][:-1] + ', ' +ret[i+1]
            del ret[i+1]
        else:
            i+=1    
    return map(deescape, ret)       

if __name__ == "__main__":
    list = ['Red, Green, Blue', 'Other Colors', 'Backslash: \\', 'Comma: ,']
    str = _listToStr(list)
    print list
    print str
    print _strToList(str)
    print 'Everything OK: ', list == _strToList(str)
    
