#!/usr/bin/env python
"""
     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/>.
"""

from Pycard import dialog, model
from Pycard.twistedsupport import twistedModel
from twisted.internet import reactor
import urllib2 
from skylive import config
from skylive.lang import language


class DumbProxyAuthMgr:
   def __init__(self):
      self.user = self.passwd = None

   def add_password(self, realm, uri, user, passwd):
      self.user = user
      self.passwd = passwd

   def find_user_password(self, realm, authuri):
      return self.user, self.passwd


# XXX Unire le due in una sola classe e agire su due derivate!!!

class proxyConf(model.PageBackground):
    
   def on_initialize(self, event):
      self.resetCfg()
      self.proxyEnabled = False
      self.proxyCfg = config.get_usrProxy()
      self.checkStatus()
      
   def checkStatus(self):
      if self.proxyCfg['useProxy'] == "yes":
         self.proxyEnabled = True
         self.components.modifyButton.enabled = True
         self.components.CheckBoxUseProxy.checked = True
         self.components.CheckBoxUseProxy.enabled = False
         self.showProxyCfg()
      else:
         self.proxyEnabled = False
         self.components.modifyButton.enabled = True
         self.components.CheckBoxUseProxy.checked = False
         self.components.CheckBoxUseProxy.enabled = True
         self.showProxyCfg()

   def on_close(self, event):
      event.skip()

   def resetCfg(self):
      self.components.proxyurl.text = ''
      self.components.proxyport.text = ''
      self.components.proxyuser.text = ''
      self.components.proxypsw.text = ''
      self.components.CheckBoxUseProxy.checked = False
   
   def showProxyCfg(self):
      
      self.components.proxyurl.text = self.proxyCfg['proxyUrl']
      self.components.proxyport.text = str(self.proxyCfg['proxyPort'])
      self.components.proxyuser.text = self.proxyCfg['proxyUsrName']
      self.components.proxypsw.text = self.proxyCfg['proxyUsrPsw']

   def on_CheckBoxUseProxy_mouseClick(self, event):
      if self.components.CheckBoxUseProxy.checked:
         if self.proxyEnabled:
            self.components.modifyButton.enabled = True
            self.components.cleanButton.enabled = True
            self.useProxy = "yes"
         else:
            self.useProxy = "no"
            self.enableCfg()
      else:
         if self.proxyEnabled:
            self.useProxy = "no"
            self.components.applyButton.enabled = True
         else:
            self.disableCfg()
            self.useProxy = "no"
         

   def enableCfg(self):
      self.components.proxyurl.enabled = True
      self.components.proxyport.enabled = True
      self.components.proxyuser.enabled = True
      self.components.proxypsw.enabled = True
      self.components.proxytest.enabled = True
      self.components.proxyurltxt.enabled = True
      self.components.proxyporttxt.enabled = True
      self.components.proxyusertxt.enabled = True
      self.components.proxypswtxt.enabled = True
      
   
   def disableCfg(self):
      self.components.proxyurl.enabled = False
      self.components.proxyport.enabled = False
      self.components.proxyuser.enabled = False
      self.components.proxypsw.enabled = False
      self.components.proxytest.enabled = False
      self.components.proxyurltxt.enabled = False
      self.components.proxyporttxt.enabled = False
      self.components.proxyusertxt.enabled = False
      self.components.proxypswtxt.enabled = False

   def doProxyTest(self, *args):

      ret = False
      authinfo = urllib2.ProxyBasicAuthHandler(DumbProxyAuthMgr())
      authinfo.add_password(None, None, args[0]['proxyUsrName'], args[0]['proxyUsrPsw'])
      proxy_url = "http://"+args[0]['proxyUrl']+":"+str(args[0]['proxyPort'])

      proxy_support = urllib2.ProxyHandler({"http" : proxy_url})

      # build a new opener that adds authentication and caching FTP handlers
      opener = urllib2.build_opener(proxy_support, authinfo, urllib2.CacheFTPHandler)

      # install it
      urllib2.install_opener(opener)

      # test it
      uri = "http://www.skylive.it/skylive-new/immagini/sandro.jpg"
      try:
         test = urllib2.urlopen(uri)
         ret = True
      except urllib2.URLError:
         ret = False

      return ret
      
   def allFields(self):
      ret = False
      if self.components.CheckBoxUseProxy.checked:
         useProxy = "yes"
      else:
         useProxy = "no"
      proxyUrl = self.components.proxyurl.text.replace(' ', '')
      proxyPort = self.components.proxyport.text.replace(' ', '')
      proxyUsrName = self.components.proxyuser.text
      proxyUsrPsw = self.components.proxypsw.text
      if proxyUrl != '' and proxyPort != '':
         if proxyUsrName.replace(' ', '') == '':
            proxyUsrName = ''
         if proxyUsrPsw.replace(' ', '') == '':
            proxyUsrPsw = ''
         ret = {'useProxy' : useProxy, 'proxyUrl' : proxyUrl, 'proxyPort' : proxyPort, 
             'proxyUsrName' : proxyUsrName, 'proxyUsrPsw' : proxyUsrPsw}
      else:
         dialog.alertDialog(self, "Please fill all Fields and retry")
         ret = False
      return ret
    

   def on_proxytest_mouseClick(self, event):
      if self.allFields():
         if self.doProxyTest(self.allFields()):
            self.useProxy = "yes"
            dialog.alertDialog(self, "Configuration successifull tested! Now you can store it")
            self.disableCfg()
            self.components.modifyButton.enabled = True
            self.components.applyButton.enabled = True
         else:
            self.useProxy = "no"
            self.components.applyButton.enabled = False
            dialog.alertDialog(self, "Configuration Error, Please check it and retry")
            
   def applyedCfg(self):
      if self.components.CheckBoxUseProxy.checked:
         useProxy = "yes"
      else:
         useProxy = "no"
      proxyUrl = self.components.proxyurl.text.replace(' ', '')
      proxyPort = self.components.proxyport.text.replace(' ', '')
      proxyUsrName = self.components.proxyuser.text
      proxyUsrPsw = self.components.proxypsw.text
      if proxyUsrName.replace(' ', '') == '':
         proxyUsrName = ''
      if proxyUsrPsw.replace(' ', '') == '':
         proxyUsrPsw = ''

      if len(proxyUsrName) > 0  and len(proxyUsrPsw)  > 0:
         proxyuseauth = 'yes'
      else:
         proxyuseauth = 'no'

      ret = {'useProxy' : useProxy, 'proxyUrl' : proxyUrl, 'proxyPort' : proxyPort,
            'proxyUsrName' : proxyUsrName, 'proxyUsrPsw' : proxyUsrPsw, 'proxyAuth': proxyuseauth}
      return ret
            
   def on_applyButton_mouseClick(self, event):
      config.put_usrProxy(self.applyedCfg())
      self.components.applyButton.enabled = False
      self.components.proxytest.enabled = False
      self.disableCfg()
      if self.proxyEnabled:
         self.components.modifyButton.enabled = True
         self.components.cleanButton.enabled = True
      self._parent.TwistedLoop.serverReconnect()


   def on_modifyButton_mouseClick(self, event):
      self.enableCfg()
      self.components.modifyButton.enabled = False
      self.components.proxytest.enabled = True
      self.components.cleanButton.enabled = True
      self.components.CheckBoxUseProxy.enabled = True
   
   def on_cleanButton_mouseClick(self, event):
      self.resetCfg()
      config.put_usrProxy(self.applyedCfg())
      self.components.proxytest.enabled = True
      self.components.applyButton.enabled = False
      self.disableCfg()
      self.components.cleanButton.enabled = False


class proxyConf2(model.Background):
   
   def on_initialize(self, event):
      self.resetCfg()
      self.proxyEnabled = False
      self.proxyCfg = config.get_usrProxy()
      self.checkStatus()
      
   def checkStatus(self):
      if self.proxyCfg['useProxy'] == "yes":
         self.proxyEnabled = True
         self.components.modifyButton.enabled = True
         self.components.CheckBoxUseProxy.checked = True
         self.components.CheckBoxUseProxy.enabled = False
         self.showProxyCfg()
      else:
         self.proxyEnabled = False
         self.components.modifyButton.enabled = True
         self.components.CheckBoxUseProxy.checked = False
         self.components.CheckBoxUseProxy.enabled = True
         self.showProxyCfg()

   def on_close(self, event):
      event.skip()

   def resetCfg(self):
      self.components.proxyurl.text = ''
      self.components.proxyport.text = ''
      self.components.proxyuser.text = ''
      self.components.proxypsw.text = ''
      self.components.CheckBoxUseProxy.checked = False
   
   def showProxyCfg(self):
      
      self.components.proxyurl.text = self.proxyCfg['proxyUrl']
      self.components.proxyport.text = str(self.proxyCfg['proxyPort'])
      self.components.proxyuser.text = self.proxyCfg['proxyUsrName']
      self.components.proxypsw.text = self.proxyCfg['proxyUsrPsw']

   def on_CheckBoxUseProxy_mouseClick(self, event):
      if self.components.CheckBoxUseProxy.checked:
         if self.proxyEnabled:
            self.components.modifyButton.enabled = True
            self.components.cleanButton.enabled = True
            self.useProxy = "yes"
         else:
            self.useProxy = "no"
            self.enableCfg()
      else:
         if self.proxyEnabled:
            self.useProxy = "no"
            self.components.applyButton.enabled = True
         else:
            self.disableCfg()
            self.useProxy = "no"
         

   def enableCfg(self):
      self.components.proxyurl.enabled = True
      self.components.proxyport.enabled = True
      self.components.proxyuser.enabled = True
      self.components.proxypsw.enabled = True
      self.components.proxytest.enabled = True
      self.components.proxyurltxt.enabled = True
      self.components.proxyporttxt.enabled = True
      self.components.proxyusertxt.enabled = True
      self.components.proxypswtxt.enabled = True
      
   
   def disableCfg(self):
      self.components.proxyurl.enabled = False
      self.components.proxyport.enabled = False
      self.components.proxyuser.enabled = False
      self.components.proxypsw.enabled = False
      self.components.proxytest.enabled = False
      self.components.proxyurltxt.enabled = False
      self.components.proxyporttxt.enabled = False
      self.components.proxyusertxt.enabled = False
      self.components.proxypswtxt.enabled = False

   def doProxyTest(self, *args):
      ret = False
      # set up authentication info
      authinfo = urllib2.ProxyBasicAuthHandler(DumbProxyAuthMgr())
      authinfo.add_password(None, None, args[0]['proxyUsrName'], args[0]['proxyUsrPsw'])
      proxy_url = "http://"+args[0]['proxyUrl']+":"+str(args[0]['proxyPort'])
    
      proxy_support = urllib2.ProxyHandler({"http" : proxy_url})
    
      # build a new opener that adds authentication and caching FTP handlers
      opener = urllib2.build_opener(proxy_support, authinfo, urllib2.CacheFTPHandler)
    
      # install it
      urllib2.install_opener(opener)
      
      # test it
      uri = "http://www.skylive.it/skylive-new/immagini/sandro.jpg"
      try:
         test = urllib2.urlopen(uri)
         ret = True
      except urllib2.URLError:
         ret = False

      return ret
      
   def allFields(self):
      ret = False
      if self.components.CheckBoxUseProxy.checked:
         useProxy = "yes"
      else:
         useProxy = "no"
      proxyUrl = self.components.proxyurl.text.replace(' ', '')
      proxyPort = self.components.proxyport.text.replace(' ', '')
      proxyUsrName = self.components.proxyuser.text
      proxyUsrPsw = self.components.proxypsw.text
      if proxyUrl != '' and proxyPort != '':
         if proxyUsrName.replace(' ', '') == '':
            proxyUsrName = ''
         if proxyUsrPsw.replace(' ', '') == '':
            proxyUsrPsw = ''
         ret = {'useProxy' : useProxy, 'proxyUrl' : proxyUrl, 'proxyPort' : proxyPort,
             'proxyUsrName' : proxyUsrName, 'proxyUsrPsw' : proxyUsrPsw}
      else:
         dialog.alertDialog(self, "Please fill all Fields and retry")
         ret = False
      return ret


   def on_proxytest_mouseClick(self, event):
      if self.allFields():
         if self.doProxyTest(self.allFields()):
            self.useProxy = "yes"
            dialog.alertDialog(self, "Configuration successifull tested! Now you can store it")
            self.disableCfg()
            self.components.modifyButton.enabled = True
            self.components.applyButton.enabled = True
         else:
            self.useProxy = "no"
            self.components.applyButton.enabled = False
            dialog.alertDialog(self, "Configuration Error, Please check it and retry")
            
   def applyedCfg(self):
      if self.components.CheckBoxUseProxy.checked:
         useProxy = "yes"
      else:
         useProxy = "no"
      proxyUrl = self.components.proxyurl.text.replace(' ', '')
      proxyPort = self.components.proxyport.text.replace(' ', '')
      proxyUsrName = self.components.proxyuser.text
      proxyUsrPsw = self.components.proxypsw.text
      if proxyUsrName.replace(' ', '') == '':
         proxyUsrName = ''
      if proxyUsrPsw.replace(' ', '') == '':
         proxyUsrPsw = ''

      if len(proxyUsrName) > 0  and len(proxyUsrPsw)  > 0:
         proxyuseauth = 'yes'
      else:
         proxyuseauth = 'no'

      ret = {'useProxy' : useProxy, 'proxyUrl' : proxyUrl, 'proxyPort' : proxyPort,
            'proxyUsrName' : proxyUsrName, 'proxyUsrPsw' : proxyUsrPsw, 'proxyAuth': proxyuseauth}
      return ret

            
   def on_applyButton_mouseClick(self, event):
      config.put_usrProxy(self.applyedCfg())
      self.components.applyButton.enabled = False
      self.components.proxytest.enabled = False
      self.disableCfg()
      if self.proxyEnabled:
         self.components.modifyButton.enabled = True
         self.components.cleanButton.enabled = True
    
   def on_modifyButton_mouseClick(self, event):
      self.enableCfg()
      self.components.modifyButton.enabled = False
      self.components.proxytest.enabled = True
      self.components.cleanButton.enabled = True
      self.components.CheckBoxUseProxy.enabled = True
   
   def on_cleanButton_mouseClick(self, event):
      self.resetCfg()
      config.put_usrProxy(self.applyedCfg())
      self.components.proxytest.enabled = True
      self.components.applyButton.enabled = False
      self.disableCfg()
      self.components.cleanButton.enabled = False


def run():
   #app = model.Application(proxyConf2, './skylive/settings/proxyconf.rsrc.py')
   app = twistedModel.TwistedApplication(proxyConf2, './gui/settings/proxyconf.rsrc.py')
   app.MainLoop()
