"""
     Copyright (C) 2007-2009 Franco Lanza <nextime@nexlab.it>
     Copyright (C) 2007-2009 Sandro Aliano <ita595@hotmail.com>
     Copyright (C) 2007-2009 Ivan Bellia <skylive@skylive.it>

     Web site: http://www.astronomix.org/trac/Skylive-NG

     This file is part of Skylive-NG.

     Skylive-NG 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 3 of the License, or
     (at your option) any later version.

     Skylive-NG is distributed in the hope that it will be useful,
     but WITHOUT ANY WARRANTY; without even the implied warranty of
     MERCHANTABILITY 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 Skylive-NG.  If not, see <http://www.gnu.org/licenses/>.
"""

import httplib
import time, os, sys, traceback
import protocol
from utils import genutils as utils
from gui import gui
from ConfigParser import SafeConfigParser
import platform
import string
from random import choice
#import md5, base64
import base64
try:
   import hashlib
   md5 = hashlib
   md5.new = hashlib.md5

except:
   import md5


class configFile(SafeConfigParser):
   
   defaults = {
               'Network': {
                          'transport': 'SSL'
                          },
               'HTTPProxy':{
                           'useproxy': 'no',
                           'proxyurl': '',
                           'proxyport': '',
                           'proxyauth': 'no',
                           'proxyauthstr':'',
                           'proxyusr':'',
                           'proxypwd':''
                           },
               'Main': 
                  {
                     'version': '0.1',
                     'revision': '5.6'
                  }, 
               'Login': {
                  'username': 'NOTSET',
                  'password': 'NOTSET'
                  },
               'UsrPreference':
                  {
                     'chatcharsize': '1',
                     'listcharsize': '7',
                     'inputcharsize': '8',
                     'pointercolor': '#FF7700',
                     'ardecfile': 'False',
                     'indi': 'False',
                     'beep':'True',
                     'popup':'True',
                     'lang':'en',
                     'usrdefpath':'',
                     'lowres':'False',
                  },
               'ExternalPrograms':
                  {
                     'indi': 'False',
                     'ardecfile': 'False',
                  },
               'Streaming':
                  {
                     'enable': 'True',
                     'ask': 'True',
                     'index': '0'
                  }
              }
   
   def __init__(self):
      # This seem to work on both win, linux, osx and also for FreeBSD.
      # I hope that it will work also on other unixes
      SafeConfigParser.__init__(self)
      self.userhome = os.path.expanduser("~")
      
      # We have a new config system. Remove all directory from oldest
      # client installs. Maybe sometime in the future we will remove those
      # lines.
      for name in ['/.SkyliveNG', '/.SkyliveNG_Pref', '/skylive-ng_chat']:
         dirname = os.path.normpath(self.userhome+name)
         if os.path.exists(dirname):
            try:
               utils.rmdir(dirname)
            except:
               print 'I cant remove %s, please remove it manually!' % dirname

      self.skyliveDir = os.path.normpath(self.userhome+"/SkyliveNG")
      self.conffile = os.path.normpath(self.skyliveDir+"/skyliveng.conf")
      self.savechatdir = os.path.normpath(self.skyliveDir+"/ChatLogs")
      self.downloadDir = os.path.normpath(self.skyliveDir+"/downloads")
      self.extraDir = os.path.normpath(self.skyliveDir+"/extra")
      self.binDir = os.path.normpath(self.skyliveDir+"/bin")

      for cdir in [self.skyliveDir, self.savechatdir, self.downloadDir, self.extraDir, self.binDir]:
         if not os.path.exists(cdir):
            try:
               os.makedirs(cdir, 0700)
            except:
               print 'Cannot create directory %s. Please verify your permissions!' % cdir
               sys.exit(0)
      if utils.platform == 'Windows':
         pathsep = ";"
      else:
         pathsep = ":"
      
      if not self.binDir in os.environ["PATH"].split(pathsep):
         os.environ["PATH"] = os.environ["PATH"]+pathsep+self.binDir
      self.bootRead()

   def readConfigFile(self):
      print 'READ'
      if not os.path.exists(self.conffile) or not os.path.isfile(self.conffile):
         if utils.platform() in ('Windows', 'Microsoft'):
            if int(sys.getwindowsversion()[0]) > 5:
               self.defaults['Streaming']['index']='1'
         self.createDefaultConfigFile()
      else:
         try:
            tochange = True
            if self.has_section('Main'):
               if self.has_option('Main', 'version'):
                  if self.has_option('Main', 'revison'):
                     # This is for an old error on 1.x version...
                     self.remove_option('Main', 'revison')
                  else:
                     if self.has_option('Main', 'revision'):
                        if self.get('Main', 'version') == self.defaults['Main']['version']:
                           if self.get('Main', 'revision') == self.defaults['Main']['revision']:
                              tochange = False
            #self.read(self.conffile)
            if tochange:
               changed = False
               for s in self.defaults.keys():
                  if not s in self.sections():
                     self.add_section(s)   
                     changed = True
                  for o in self.defaults[s].keys():
                     if s=='Main' and o in ['version', 'revision']:
                        if self.has_option(s, o):
                           if self.get(s, o) != self.defaults[s][o]:
                              self.set(s, o, self.defaults[s][o])
                              changed = True
                        else:
                           self.set(s, o, self.defaults[s][o])
                     else:
                        if not o in self.options(s):
                           self.set(s, o, self.defaults[s][o])
                           changed = True
                     # XXX An this is cause Windows Vista and Windows 7
                     # won't work good with ogg streaming...
                     # I hope it will change in future, as 
                     # WMP and mp3 streaming have very high latency..
                     if s=='Streaming' and o=='index':
                        if utils.platform() in ('Windows', 'Microsoft'):
                           if int(sys.getwindowsversion()[0]) > 5:
                              self.defaults[s][o]='1'
                              self.set(s, o, self.defaults[s][o])
                              changed = True
                     # End of the windows Hack.
                     if s=='UsrPreference' and o=='chatcharsize':
                        if int(self.get(s, o)) > 4:
                           self.set(s, o, self.defaults[s][o])
                           changed = True
                     
               if changed:
                  self.saveConfigFile()
         except:
            print 'Error parsing config file'

   def bootRead(self):
      if os.path.exists(self.conffile) and os.path.isfile(self.conffile):
         self.read(self.conffile)

   def get(self, sect, var):
      if os.path.exists(self.conffile) and os.path.isfile(self.conffile):
         return SafeConfigParser.get(self, sect, var)
      else:
         return self.defaults[sect][var]

   def saveConfigFile(self):
      print 'SAVE CONFIG'
      fd = open(self.conffile, "w")
      self.write(fd)
      fd.close()


   def changeLoginInfos(self, counterlogin=0, runtime=False):
      print 'CHANGE LOGIN INFO '
      self.user=None
      cleanpwd=None
      while not self.user or not cleanpwd:
         if counterlogin > 3:
            sys.exit(0)
            break
         self.user, cleanpwd=gui.Login()
         counterlogin=counterlogin+1

      if self.user != "stoplogin" and cleanpwd != "stoplogin":
         self.set('Login', 'username', self.user)
         m = md5.new(cleanpwd)
         self.pwd =  str(m.hexdigest())    
         self.set('Login', 'password', self.pwd)
         self.saveConfigFile() 
         

      else:
         if runtime:
            self.readConfigFile()
         else:
            sys.exit(0)



   def createDefaultConfigFile(self):
      for sect in self.defaults:
         try:
            self.add_section(sect)
         except:
            pass
         for opt in self.defaults[sect]:
            self.set(sect, opt, self.defaults[sect][opt])
      self.set('UsrPreference', 'usrdefpath', self.downloadDir)
      # Work around for OSX: we need a more bigger characters here!
      if platform.system() == 'Darwin':
         self.put_usrCharSizes('11', '10', '11')

      # Ask for login infos
      self.changeLoginInfos(1)

   def put_usrProxy(self, args):
      self.read(self.conffile)
      self.set('HTTPProxy', 'useproxy', args['useProxy'])
      self.set('HTTPProxy', 'proxyurl', args['proxyUrl'])
      self.set('HTTPProxy', 'proxyport', args['proxyPort'])
      self.set('HTTPProxy', 'proxyusr', args['proxyUsrName'])
      self.set('HTTPProxy', 'proxypwd', args['proxyUsrPsw'])
      if args['proxyAuth'] == 'yes':
         proxyauthstr = base64.b64encode(args['proxyUsrName']+':'+args['proxyUsrPsw'])
         self.set('HTTPProxy', 'proxyauthstr', proxyauthstr)
         self.set('HTTPProxy', 'proxyauth', 'yes')
      else:
         self.set('HTTPProxy', 'proxyauthstr', "")
         self.set('HTTPProxy', 'proxyauth', 'no')
      self.saveConfigFile()


   def put_usrDefaltPath(self, path):
      self.set('UsrPreference', 'usrdefpath', path)
      self.saveConfigFile()
   

   def put_usrCharSizes(self, chatsize=False, listsize=False, inputsize=False):
      if chatsize:
         self.set('UsrPreference', 'chatcharsize', chatsize)
      if listsize:
         self.set('UsrPreference', 'listcharsize', listsize)
      if inputsize:
         self.set('UsrPreference', 'inputcharsize', inputsize)
      if chatsize or listsize or inputsize:
         self.saveConfigFile()

   def put_usrPointerColor(self, color="#FF7700"):
      if color:
         self.set('UsrPreference', 'pointercolor', color)
         self.saveConfigFile()

   def put_extProgram(self, pref='False'):
      self.set('ExternalPrograms', 'ardecfile', pref)
      self.saveConfigFile()

   def put_extINDIProgram(self, pref='False'):
      self.set('ExternalPrograms', 'indi', pref)
      self.saveConfigFile()

   def put_usrLang(self, lang='en'):
      self.set('UsrPreference', 'lang', lang)
      self.saveConfigFile()   

   def get_usrLang(self):
      try:
         lang = self.get('UsrPreference', 'lang')
      except:
         lang = 'en'
      return lang
   
   def put_pvtPref(self, b=False, p=False):
      if b:
         self.set('UsrPreference', 'beep', str(b))
         self.usrBeep = b
      if p:
         self.set('UsrPreference', 'popup', str(p))
         self.usrPopup = p
      if b or p:
         self.saveConfigFile()   

   def put_lowResPref(self, pref='False'):
      self.set('UsrPreference', 'lowres', pref)
      self.saveConfigFile()


#########################################################################################
CFile = configFile()


def initialize():
   CFile.readConfigFile()

def getUsername():
   return CFile.get('Login', 'username')

def getPassword():
   return 'HASH:'+CFile.get('Login', 'password')

def changeLoginCredentials(count=0):
   if count == 0:
      val=1
   else:
      val = count
   return CFile.changeLoginInfos(val, runtime=True)


def get_usrDefaultPath():
   return CFile.get('UsrPreference', 'usrdefpath')

def put_usrDefaultPath(path):
   CFile.put_usrDefaltPath(path)

def get_usrCharSizes():
   ret = {'chatsize' : CFile.get('UsrPreference', 'chatcharsize'), 
         'listsize': CFile.get('UsrPreference', 'listcharsize'), 
         'inputsize': CFile.get('UsrPreference', 'inputcharsize')}
   return ret

def put_usrCharSizes(chat=False, list=False, input=False):
   CFile.put_usrCharSizes(chat, list, input)

def get_usrProxy():
   try:
      usr = CFile.get('HTTPProxy','proxyusr')
      pwd = CFile.get('HTTPProxy','proxypwd')
   except:
      CFile.set('HTTPProxy','proxyusr', '')
      CFile.set('HTTPProxy','proxypwd', '')
   ret = {'useProxy': CFile.get('HTTPProxy', 'useproxy'),
          'proxyUrl':  CFile.get('HTTPProxy', 'proxyurl'),
          'proxyPort': CFile.get('HTTPProxy', 'proxyport'),
          'proxyAuth': CFile.get('HTTPProxy', 'proxyauth'),
          'proxyAuthStr': CFile.get('HTTPProxy','proxyauthstr'),
          'proxyUsrName': CFile.get('HTTPProxy','proxyusr'),
          'proxyUsrPsw': CFile.get('HTTPProxy','proxypwd')}
         
   return ret

def put_usrProxy(args):
   CFile.put_usrProxy(args)

def put_usrPointerColor(color):
   CFile.put_usrPointerColor(color)

def get_usrPointerColor():
   return CFile.get('UsrPreference', 'pointercolor')

def put_extProgram(pref='False'):
   CFile.put_extProgram(pref)

def put_extINDIProgram(pref='False'):
   CFile.put_extINDIProgram(pref)

def get_extProgram():
   return CFile.get('ExternalPrograms', 'ardecfile')

def get_extINDIProgram():
   return CFile.get('ExternalPrograms', 'indi')

def put_usrLang(arg):
   CFile.put_usrLang(arg)

def get_usrLang():
   return CFile.get_usrLang()

def put_pvtPref(b=False, p=False):
   CFile.put_pvtPref(str(b), str(p))

def get_pvtPref():
   if CFile.get('UsrPreference', 'beep') == 'True':
      b = True
   else:
      b = False
   if CFile.get('UsrPreference', 'popup') == 'True':
      p = True
   else:
      p = False
   return [b, p]

def get_lowResPref(when='normal'):
   if CFile.get('UsrPreference', 'lowres') == 'True':
      return True
   return False


def put_lowResPref(pref=False):
   toPut = 'False'
   if pref:
      toPut = 'True'
   CFile.put_lowResPref(toPut)


def get_streamingPref():
   enable = CFile.get('Streaming', 'enable')
   ask = CFile.get('Streaming', 'ask')
   return [enable, ask]

def get_streamingIndex():
   return CFile.get('Streaming', 'index')

def set_streamingIndex(idx=0):
   CFile.set('Streaming', 'index', str(idx))
   CFile.saveConfigFile()

def put_streamingPref(enable='True', ask='True'):
   e='False'
   a='False'
   if enable:
      e='True'
   if ask:
      a='True'
   CFile.set('Streaming','ask', a)
   CFile.set('Streaming','enable', e)
   CFile.saveConfigFile()


