import wx
import wx.xrc as xrc
import string
import sys
import xmlrpclib
import base64
import string
from os.path import join

from  localization import LanguageModule
from ipodder.FeedManagerConnector import *
from urllibtransport import UrllibTransport

from ipodder.configuration import determine_paths

class AskForUserGUI(wx.App):
    def __init__(self, config):
        self.config = config
        
        paths = determine_paths();        
        self.sourcefile = join(paths['gui'],'AskForUserGui.xrc')        
        wx.App.__init__(self, False, None)

    def _(self,key):
        return self.m_stringtable.GetText(self.m_currentlanguage,key)
    
    def OnInit(self):        
        res = xrc.XmlResource(self.sourcefile)
        #put here all elements
        self.frame = res.LoadDialog(None,"frame_askuser")
        self.username = xrc.XRCCTRL(self.frame,"text_ctrl_username")        
        self.password = xrc.XRCCTRL(self.frame,"text_ctrl_password")    
        self.button_ok = xrc.XRCCTRL(self.frame,"button_ok")
        self.button_cancel = xrc.XRCCTRL(self.frame,"button_cancel")

	    #proxy controls
    	self.proxy_checkbox = xrc.XRCCTRL(self.frame, "Proxy_CheckBox")
    	self.proxy_address_label = xrc.XRCCTRL(self.frame, "Proxy_Address_label")
    	self.proxy_address = xrc.XRCCTRL(self.frame, "Proxy_Address_ctrl")
    	self.proxy_port_label = xrc.XRCCTRL(self.frame, "Proxy_Port_label")
    	self.proxy_port = xrc.XRCCTRL(self.frame, "Proxy_Port")
    	self.proxy_auth_username_label = xrc.XRCCTRL(self.frame, "ID_Auth_Username_label")
    	self.proxy_auth_username = xrc.XRCCTRL(self.frame, "ID_Auth_Username")
    	self.proxy_auth_password_label = xrc.XRCCTRL(self.frame, "ID_Auth_Password_label")
    	self.proxy_auth_password = xrc.XRCCTRL(self.frame, "ID_Auth_Password")

        #events
        wx.EVT_BUTTON(self, xrc.XRCID("button_ok"),self.OnOk)
        wx.EVT_BUTTON(self, xrc.XRCID("button_cancel"),self.OnCancel)
        wx.EVT_CHECKBOX(self, xrc.XRCID("Proxy_CheckBox"), self.OnProxy)

        wx.EVT_TEXT_ENTER(self, xrc.XRCID("text_ctrl_username"),self.OnOk)
        wx.EVT_TEXT_ENTER(self, xrc.XRCID("text_ctrl_password"),self.OnOk)

        wx.EVT_TEXT_ENTER(self, xrc.XRCID("button_ok"),self.OnOk)
        wx.EVT_TEXT_ENTER(self, xrc.XRCID("button_cancel"),self.OnCancel)
        
        self.m_currentlanguage = 'en'
        self.m_stringtable = LanguageModule.StringTable(self.m_currentlanguage)  
	
        self.frame.Show(1)
        self.SetTopWindow(self.frame)

        return True

    def OnProxy(self,event):
        """ Show the other fields needed for setting the proxy """
        size = None;
    	if self.proxy_checkbox.IsChecked():
    	    self.proxy_address_label.Show(True)
    	    self.proxy_address.Show(True)
    	    self.proxy_port_label.Show(True)
    	    self.proxy_port.Show(True)
    	    self.proxy_auth_username_label.Show(True)
    	    self.proxy_auth_username.Show(True)
    	    self.proxy_auth_password.Show(True)
    	    self.proxy_auth_password_label.Show(True)
            size = wx.Size(350,460);
    	else:
    	    self.proxy_address_label.Show(False)
    	    self.proxy_address.Show(False)
    	    self.proxy_port_label.Show(False)
    	    self.proxy_port.Show(False)
    	    self.proxy_auth_username_label.Show(False)
    	    self.proxy_auth_username.Show(False)
    	    self.proxy_auth_password.Show(False)
    	    self.proxy_auth_password_label.Show(False)
            size = wx.Size(350,360);
    
        
    	self.frame.Show(0)
        self.frame.SetSize(size);
    	self.frame.Show(1)

    def GetUserData(self):
        user = self.username.GetValue().strip()
        password = self.password.GetValue().strip()
	return user,password


    def GetProxyData(self):
        if self.proxy_checkbox.IsChecked():
            proxy_address = self.proxy_address.GetValue().strip()
    	    proxy_port = self.proxy_port.GetValue().strip()
    	    proxy_auth_username = self.proxy_auth_username.GetValue().strip()
    	    proxy_auth_password = self.proxy_auth_password.GetValue().strip()
    	    #Watch if the proxy_port is empty then what should be the default?
    	    if proxy_port == "":
    	        proxy_port = '80';
                
    	    return proxy_address, proxy_port, proxy_auth_username, proxy_auth_password
        else:
    	    return u"",u"",u"",u""

    def OnOk(self,event):
        current_cursor = self.frame.GetCursor();
        self.frame.SetCursor( wx.StockCursor(wx.CURSOR_WAIT) );      
        
        username, password = self.GetUserData()                    
        proxy_address, proxy_port, proxy_auth_username, proxy_auth_password = self.GetProxyData();
       
        #Test the proxy-settings.
        proxyconf = ProxyConfiguration(proxy_address, proxy_port, proxy_auth_username, proxy_auth_password, self.proxy_checkbox.IsChecked())
        if self.proxy_checkbox.IsChecked():                        
            if False == proxyconf.TestProxy():
                e = proxyconf.GetLastError();
                self.frame.SetCursor( current_cursor );                        
                alert = wx.MessageDialog(self.frame, self._("str_bad_proxy") + "\n" + str(e), style=wx.OK|wx.ICON_EXCLAMATION)
                alert.ShowModal()
                alert.Destroy()
                return
        
        #Calculate password hash
        import string, md5
        from random import choice
        password_salt = "";
        password_hash = ""
                
        if len(password) > 0:                        
            password_salt = ''.join([choice(string.letters+string.digits) for i in range(16)])
            password_salt = password_salt;
            password_hash = md5.md5(password + str(password_salt)).hexdigest();
        
        #Test if PodNova.com knows this user        
        fm_userid = FeedManagerUserId(username, password_hash, password_salt, proxyconf);
        fm_userid.start();
        fm_userid.join();
        user_guid = fm_userid.GetUserGuid();
        
        if user_guid == "":           
            self.frame.SetCursor( current_cursor );
            alert = wx.MessageDialog(self.frame, self._("str_podnova_unknown_user"), caption=self._("str_error_dialog_title"), style=wx.OK|wx.ICON_ERROR)        
            alert.ShowModal()
            alert.Destroy()                                        
            return;
        
        self.config.use_proxy_server = proxyconf.GetUseProxy();
        self.config.http_proxy_server = proxy_address
        self.config.http_proxy_port =  proxy_port
        self.config.http_proxy_username = proxy_auth_username
        self.config.http_proxy_password = proxy_auth_password
        self.config.user_account_name = username
        self.config.user_account_password_salt = password_salt;
        self.config.user_account_password_hash = password_hash
        
        self.config.flush()
                                
        self.frame.Destroy()
        self.ExitMainLoop()
      

    def OnCancel(self,event):
        self.frame.Destroy()
        self.ExitMainLoop()
   
if __name__ == "__main__":
    base = '.'
    config = 'test.txt'
    AskUser = AskForUserGUI(config)
    AskUser.MainLoop()
