#!/usr/bin/python2.5

# vim:ts=4:et:nowrap

import sys
import os
import commands
import hildon
import pickle
import google_service
import gpe_service
import erminigcfg
import processevents
import datetime
import getopt
import gtk
import socket

from utils import *

ERMINIG_VERSION="0.3.1"

class erminigApp(hildon.Program):
    """Erminig Application"""

    def __init__(self, profiles, googleAccess, gpeAccess, config, useProxy):
        self.profiles = profiles
        self.googleAccess = googleAccess
        self.gpe_access = gpeAccess.gpe_access
        self.currentcfg = config.currentcfg
        self.useProxy = useProxy

        hildon.Program.__init__(self)

        self.debug_enabled = 0

        #Set the Glade file
        self.gladefile = sys.path[0] + "/" + "erminig.glade"
        self.wTree = gtk.glade.XML(self.gladefile, "mainWindow")
        
        #Test to hildonize
        self.app = hildon.Program()        
        self.window = hildon.Window()
        self.mainwindow = self.wTree.get_widget("mainWindow")
        self.window.set_title(self.mainwindow.get_title())
        self.window.connect("destroy", self.on_Quit)
        self.app.add_window(self.window)
        self.vbox1 = self.wTree.get_widget("vbox1")
        self.vbox1.reparent(self.window)
        self.tmpwindow = self.wTree.get_widget("mainWindow")
        self.progressbar = self.wTree.get_widget("progressbar")
        
        menu = gtk.Menu()
        self.mainMenu = self.wTree.get_widget("menubar1")
        for child in self.mainMenu.get_children():
            child.reparent(menu) 
        self.window.set_menu(menu)
        self.mainMenu.destroy() 
        
        self.tmpwindow.destroy()
        self.window.show_all()
        
        
        

        #Create our dictionay and connect it
        dic = {"on_mainWindow_destroy" : self.on_Quit
                , "on_AddProfile" : self.OnAddProfile
                , "on_EditProfile" : self.on_EditProfile
                , "on_UpdateProfile" : self.on_UpdateProfile
                , "on_UpdateAll" : self.on_UpdateAll
                , "on_DelProfile" : self.OnDelProfile
                , "on_google_parameters_activate" : self.edit_google_params
                , "on_quit_activate" : self.on_Quit
                , "on_about_activate" : self.showAbout
                , "on_debugmode_activate" : self.debugmode
                , "on_proxymode_activate" : self.proxymode
                , "on_proxyParameters_activate" : self.edit_proxy_params}
        self.wTree.signal_autoconnect(dic)

        #Here are some variables that can be reused later
        self.cProfileObject = 0
        self.cName = 1
        self.cGoogleCalendarTitle = 2
        self.cGoogleCalendarId = 3
        self.cGpeCalendarTitle = 5
        self.cGpeCalendarId = 6
        self.cEnabled = 7
        self.cIcon = 10
        self.cLastUpdate = 11
        self.sName = "Name"
        self.sEnabled = "Enabled"
        self.sLastUpdate = "Last update"

        #Get the treeView from the widget Tree
        self.profileView = self.wTree.get_widget("profileView")
        #Add all of the List Columns to the cmdView
        
        self.AddProfileListCheckboxColumn(self.sEnabled, self.cIcon)
        self.AddProfileListTextColumn(self.sName, self.cName)
        self.AddProfileListTextColumn(self.sLastUpdate, self.cLastUpdate)
        

        #Create the listStore Model to use with the cmdView
        self.profileList = gtk.ListStore(gobject.TYPE_PYOBJECT
                                    , gobject.TYPE_STRING
                                    , gobject.TYPE_STRING
                                    , gobject.TYPE_STRING
                                    , gobject.TYPE_STRING
                                    , gobject.TYPE_STRING
                                    , gobject.TYPE_STRING
                                    , gobject.TYPE_STRING
                                    , gobject.TYPE_STRING
                                    , gobject.TYPE_BOOLEAN
                                    , str
                                    , gobject.TYPE_STRING)
        #Attache the model to the treeView
        self.profileView.set_model(self.profileList)
        self.updateProfilesList()

    def showAbout(self, widget):
        message = "This is Erminig " + ERMINIG_VERSION + "\n\n"
        message = message + "Currently maintained by: Pascal Jermini\n"
        message = message + "Original Author: David Hautbois\n\n"
        message = message + "Homepage: http://erminig.garage.maemo.org"
        dialog = hildon.Note("information", (self.mainwindow, message, gtk.STOCK_DIALOG_INFO))
        dialog.set_button_text("Ok")
        response = dialog.run() 
        dialog.destroy()


    def updateProfilesList(self):
        # Populate the profile list...
        self.profileList.clear()
        for i in self.profiles.profileList:
                self.profileList.append(i)
        
    def debugmode(self, msg):
    
        if (self.debug_enabled == 0):
            #Write to log file
            self.debug_enabled = 1
            self.saveout = sys.stdout
            self.saveerr = sys.stderr
            self.fsock = open(os.path.expanduser('~/MyDocs/erminig_debug.txt'), 'w')
            sys.stdout = self.fsock
            sys.stderr = self.fsock
        else:
            #Write to std
            self.debug_enabled = 0
            sys.stdout = self.saveout
            sys.stderr = self.saveerr
            self.fsock.close()
            
            
    def proxymode(self, msg):
        if not self.googleAccess.proxy_enabled:
            printd("proxymode : enabled")
            self.googleAccess.proxy_enabled = True
        else:
            printd("proxymode : disabled")
            self.googleAccess.proxy_enabled = False

        self.googleAccess.reconnect()
        self.currentcfg.load_configuration()
        self.refresh_widgets()
        
    def AddProfileListTextColumn(self, name, columnId):
        """This function adds a column to the list view.
        First it create the gtk.TreeViewColumn and then set
        some needed properties"""

        column = gtk.TreeViewColumn(name, gtk.CellRendererText()
            , text=columnId)
        column.set_resizable(True)
        column.set_sort_column_id(columnId)
        self.profileView.append_column(column)
        
        
    def AddProfileListCheckboxColumn(self, name, columnId):
        """This function adds a column to the list view.
        First it create the gtk.TreeViewColumn and then set
        some needed properties"""
        
        
        self.column = gtk.TreeViewColumn()
        self.profileView.append_column(self.column)
        self.renderer1 = gtk.CellRendererPixbuf()
        self.column.pack_start(self.renderer1, False)        
        self.column.set_attributes(self.renderer1, stock_id=columnId)
        
                

    def on_Quit(self, widget):
        """Called when the application is going to quit"""
        gtk.main_quit()
        
        
    def on_UpdateProfile(self, widget):
        """Called when  the user want to update a profile"""
        # Get the selection in the gtk.TreeView
        selection = self.profileView.get_selection()
        # Get the selection iter
        model, selection_iter = selection.get_selected()
        
        if (selection_iter):
            """There is a selection, so now get the the value at column
            self.cCmdObject, the Cmd Object"""
            profile = self.profileList.get_value(selection_iter, self.cProfileObject)
            if (profile.enabled == True):
                # Updating the profile (todo)
                MyProcessEvent=processevents.ProcessEventsObj(self.googleAccess.google_access, self.gpe_access, self.currentcfg)
                result = MyProcessEvent.updateall(profile.name,
                                                                        self.window,
                                                                        self.progressbar)
                if (result == 0):
                    print("All tasks done")
                    self.progressbar.set_text("Success update !")
                elif (result == 2):
                    print("Abort")
                    self.progressbar.set_text("Update aborted !")
                elif (result == 1):
                    print ("Aborted, invalid events detected")
                    self.displayinvalidevents(MyProcessEvent.invalid_events)

        self.profiles.init_profiles()
        self.updateProfilesList()
    
    
    def on_UpdateAll(self, widget):
        """Update all profiles"""
        
        MyProcessEvent=processevents.ProcessEventsObj(self.googleAccess.google_access, self.gpe_access, self.currentcfg)
        profiles = self.profileList
        for profile in profiles:
            print "on_UpdateAll : Profile to update : " + profile[0].name
            if (profile[0].enabled == True):
                result = MyProcessEvent.updateall(profile[0].name, self.window,
                                        self.progressbar)
                if (result == 0):
                    print("All tasks done")
                else:
                    print ("Aborted, invalid events detected")
                    self.displayinvalidevents(result)
        self.progressbar.set_text("Success update !")    

        self.profiles.init_profiles()
        self.updateProfilesList()
    

    def on_EditProfile(self, widget):
        """Called when the user wants to edit a profile entry"""

        # Get the selection in the gtk.TreeView
        selection = self.profileView.get_selection()
        # Get the selection iter
        model, selection_iter = selection.get_selected()

        if (selection_iter):
            """There is a selection, so now get the the value at column
            self.cCmdObject, the Cmd Object"""
            profile = self.profileList.get_value(selection_iter, self.cProfileObject)
            
            # Create the profile dialog, based off of the current selection
            print profile.getList_cfg()
            print profile
            profileDlg = profileDialog(profile
                                   , self.googleAccess.google_access.googlecalendars
                                   , self.gpe_access.gpecalendars);
            result,newProfile = profileDlg.run()
            
            while True:
                if ((result == gtk.RESPONSE_OK) & 
                       (newProfile.name <>"")):
                    self.profileList.set(selection_iter
                            , self.cProfileObject, newProfile
                            , self.cName, newProfile.name
                            , self.cGoogleCalendarTitle
                            , newProfile.googlecalendartitle
                            , self.cGoogleCalendarId
                            , newProfile.googlecalendarid
                            , self.cGpeCalendarTitle
                            , newProfile.gpecalendartitle
                            , self.cGpeCalendarId, newProfile.gpecalendarid
                            , self.cEnabled, newProfile.enabled
                            , self.cIcon, newProfile.icon())
                    self.currentcfg.write_profile(newProfile.name
                            , newProfile.googlecalendartitle
                            , newProfile.googlecalendarid
                            , newProfile.gpecalendartitle
                            , newProfile.gpecalendarid
                            , newProfile.timezone
                            , newProfile.gpeupdate
                            , newProfile.googleupdate
                            , newProfile.enabled
                            , newProfile.startdate
                            , newProfile.accesslevel)
                    
                    return
                elif (result == gtk.RESPONSE_CANCEL):
                    return
                profileDlg = profileDialog(newProfile);
                result,newProfile = profileDlg.run()
                
                
    def edit_google_params(self, widget):
        """Called when the user wants to edit google parameters"""

        googleDlg = googleDialog(self.currentcfg.google_login
                                 , self.currentcfg.google_password);
        result, google_login, google_password = googleDlg.run()
            
        while True:
            if ((result == gtk.RESPONSE_OK) & 
                   (google_login <>"")):
                self.currentcfg.write_google_parameters(google_login
                                                        ,google_password)
                self.currentcfg.google_login = google_login
                self.currentcfg.google_password = google_password
                self.googleAccess.reconnect()
                self.refresh_widgets()
                return
            elif (result == gtk.RESPONSE_CANCEL):
                return
            googleDlg = googleDialog(self.currentcfg.google_login
                                     , self.currentcfg.google_password);
            google_login, google_password = googleDialog.run()  
                   
    
    def edit_proxy_params(self, widget):
        """Called when the user wants to edit proxy parameters"""

        proxyDlg = proxyDialog(self.currentcfg.http_proxy
                                 , self.currentcfg.https_proxy
                                 , self.currentcfg.user_proxy
                                 , self.currentcfg.password_proxy);
        result, http_proxy, https_proxy, user_proxy, password_proxy = proxyDlg.run()
            
        while True:
            if ((result == gtk.RESPONSE_OK)):
                self.currentcfg.write_proxy_parameters(http_proxy
                                                        ,https_proxy
                                                        ,user_proxy
                                                        ,password_proxy)
                self.currentcfg.http_proxy = http_proxy
                self.currentcfg.https_proxy = https_proxy
                self.currentcfg.user_proxy = user_proxy
                self.currentcfg.password_proxy = password_proxy
                self.refresh_widgets()
                return
            elif (result == gtk.RESPONSE_CANCEL):
                return
            proxyDlg = proxyDialog(self.currentcfg.http_proxy
                                 , self.currentcfg.https_proxy
                                 , self.currentcfg.user_proxy
                                 , self.currentcfg.password_proxy);
            http_proxy, https_proxy, user_proxy, password_proxy = proxyDialog.run() 

    def OnAddProfile(self, widget):
        """Called when the use wants to add a cmd"""
        # Create the dialog, show it, and store the results
        profileDlg = profileDialog(None
                                   , self.googleAccess.google_access.googlecalendars
                                   , self.gpe_access.gpecalendars);
        result,newProfile = profileDlg.run()
        
        while True:            
            if (result == gtk.RESPONSE_OK):
                tmp_profile = newProfile.getList_treeview()
                self.profileList.append(tmp_profile)
                print tmp_profile
                tmp_profile = newProfile.getList_cfg()
                self.currentcfg.write_profile(newProfile.name,
                                          newProfile.googlecalendartitle,
                                          newProfile.googlecalendarid,
                                          newProfile.gpecalendartitle,
                                          newProfile.gpecalendarid,
                                          "",
                                          0,
                                          "1970-01-01T01:01:01.000Z",
                                          newProfile.enabled,
                                          newProfile.startdate,
                                          newProfile.accesslevel)
                self.refresh_widgets()
                return
            elif (result == gtk.RESPONSE_CANCEL):
                return
            profileDlg = profileDialog(newProfile);
            result,newProfile = profileDlg.run()
          
            
    def OnDelProfile(self, widget):
        # Get the selection in the gtk.TreeView
        selection = self.profileView.get_selection()
        # Get the selection iter
        model, selection_iter = selection.get_selected()
        if (selection_iter):
            profile = self.profileList.get_value(selection_iter, self.cProfileObject)
            delDlg = delDialog(profile);
            result = delDlg.run()
            if (result == gtk.RESPONSE_OK):
                result = self.profileList.remove(selection_iter)
                self.currentcfg.delete_profile(profile.name)
                
                
    def displayinvalidevents(self, result):
        
        invalideventsDlg = invalideventsDialog(result);
        result = invalideventsDlg.run()

    def show_error_dlg(self, error_string):
        """This Function is used to show an error dialog when
        an error occurs.
        error_string - The error string that will be displayed
        on the dialog.
        """
        error_dlg = gtk.MessageDialog(type=gtk.MESSAGE_ERROR
                    , message_format=error_string
                    , buttons=gtk.BUTTONS_OK)
        error_dlg.run()
        error_dlg.destroy()
        
    def refresh_widgets(self):
        
        self.addprofile_btn = self.wTree.get_widget("tbAddProfile")
        self.updateprofile_btn = self.wTree.get_widget("tbUpdateProfile")
        if self.googleAccess.google_access.isgoogleready == 0:
            self.addprofile_btn.set_sensitive(False)
            self.updateprofile_btn.set_sensitive(False)
            self.progressbar.set_text(self.googleAccess.google_access.error)
        else:
            self.addprofile_btn.set_sensitive(True)
            self.updateprofile_btn.set_sensitive(True)
            self.progressbar.set_text("")
            

class profileDialog:
    """This class is used to show profileDlg"""

    def __init__(self, profile = None
                 , googlecalendars = None
                 , gpecalendars = None):
        """Initialize the class.
        profile - a Profile object"""

        #setup the glade file
        self.gladefile = sys.path[0] + "/" + "erminig.glade"
        #setup the cmd that we will return
        if (profile):
            #They have passed a profile object
            self.profile = Profile(profile.name
                                   , profile.googlecalendarid
                                   , profile.googlecalendartitle
                                   , profile.gpecalendarid
                                   , profile.gpecalendartitle
                                   , profile.timezone
                                   , profile.gpeupdate
                                   , profile.googleupdate
                                   , profile.enabled
                                   , profile.startdate
                                   , profile.accesslevel)
            self.edit = True
        else:
            #Just use a blank cmd
            self.profile = Profile()
            self.edit = False
        self.googlecalendars = googlecalendars
        self.gpecalendars = gpecalendars
        

    def run(self):
        """This function will show the cmdDlg"""

        #load the dialog from the glade file
        self.wTree = gtk.glade.XML(self.gladefile, "profileDlg")
        
        #Get the actual dialog widget
        self.dlg = self.wTree.get_widget("profileDlg")
        #Get all of the Entry Widgets and set their text
        self.name_entry = self.wTree.get_widget("name_entry")
        
        #Adding the date editor widget
        dateeditor = hildon.DateEditor()
        self.empty_zone = self.wTree.get_widget("table2")
        self.empty_zone.attach(dateeditor, 1, 2, 5, 6, gtk.EXPAND, gtk.EXPAND)
        dateeditor.show()
        
        self.name_entry.set_text(self.profile.name)
        
        self.googlecalendar_combo = self.wTree.get_widget("googlecalendar_combo")
        liststore = gtk.ListStore(str)
        cell = gtk.CellRendererText()
        self.googlecalendar_combo.pack_start(cell)
        self.googlecalendar_combo.add_attribute(cell,'text',0)
        self.googlecalendar_combo.set_active(0)
        for calendar in self.googlecalendars:
            print calendar[1]
            liststore.append([calendar[1]])
        self.googlecalendar_combo.set_model(liststore)    
        
        model = self.googlecalendar_combo.get_model()
        i = 0
        for item in model:
            if item[0] == self.profile.googlecalendartitle:
                self.googlecalendar_combo.set_active(i)
            i = i + 1
            
        self.gpecalendar_combo = self.wTree.get_widget("gpecalendar_combo")
        liststore = gtk.ListStore(str)
        cell = gtk.CellRendererText()
        self.gpecalendar_combo.pack_start(cell)
        self.gpecalendar_combo.add_attribute(cell,'text',0)
        self.gpecalendar_combo.set_active(0)
        for calendar in self.gpecalendars:
            print calendar[1]
            liststore.append([calendar[1]])
        self.gpecalendar_combo.set_model(liststore)    
        
        model = self.gpecalendar_combo.get_model()
        i = 0
        for item in model:
            if item[0] == self.profile.gpecalendartitle:
                self.gpecalendar_combo.set_active(i)
            i = i + 1       
        
        self.enabled_cb = self.wTree.get_widget("enabled_cb")
        print "Checkbox : %s" % (self.profile.enabled)
        self.enabled_cb.set_active(self.profile.enabled)
        
        print "accesslevel : " + self.profile.accesslevel
        self.readonly_cb  = self.wTree.get_widget("readonly_cb")
        if (self.profile.accesslevel == "read"): 
            print "read only !!!!!!!!!!!!!!!!!!" 
            self.readonly_cb.set_active(True)
        
        if (self.edit):
            self.gpecalendar_combo.set_sensitive(False)
            self.googlecalendar_combo.set_sensitive(False)
            dateeditor.set_sensitive(False)
            self.name_entry.set_sensitive(False)
            self.readonly_cb.set_sensitive(False)

        #run the dialog and store the response
        self.result = self.dlg.run()
        #get the value of the entry fields
        self.profile.name = self.name_entry.get_text()
        
        model = self.googlecalendar_combo.get_model()
        self.profile.googlecalendartitle = \
            model[self.googlecalendar_combo.get_active()][0]
        self.profile.googlecalendarid = \
            [x[0] for x in self.googlecalendars \
             if self.profile.googlecalendartitle in x[1]][0]
        self.profile.accesslevel = \
            [x[3] for x in self.googlecalendars \
             if self.profile.googlecalendartitle in x[1]][0]
        print "Selected Google calendar title : " + self.profile.googlecalendartitle
        print "Selected Google calendar id : " + self.profile.googlecalendarid
        print "Selected Google access level : " + self.profile.accesslevel
        
        model = self.gpecalendar_combo.get_model()
        self.profile.gpecalendartitle = \
            model[self.gpecalendar_combo.get_active()][0]
        self.profile.gpecalendarid = \
            str([x[0] for x in self.gpecalendars \
                 if self.profile.gpecalendartitle in x[1]][0])
        print "Selected Gpe calendar title : " + self.profile.gpecalendartitle
        print "Selected Gpe calendar id : " + self.profile.gpecalendarid
        
        self.profile.timezone = \
            [x[2] for x in self.googlecalendars \
             if self.profile.googlecalendartitle in x[1]][0]
        
        self.profile.enabled = self.enabled_cb.get_active()
        self.profile.startdate = "%s-%02d-%02d" %(dateeditor.get_year(),
                                                                   dateeditor.get_month(),
                                                                   dateeditor.get_day())
        
        if (self.readonly_cb.get_active()):
           self.profile.accesslevel = "read"
           

        
        
        #we are done with the dialog, destory it
        self.dlg.destroy()

        #return the result and the cmd
        return self.result,self.profile
    

class googleDialog:
    """This class is used to show profileDlg"""

    def __init__(self, gmailaddress = "", gmailpassword = ""):
        """Initialize the class.
        profile - a Profile object"""

        #setup the glade file
        self.gladefile = sys.path[0] + "/" + "erminig.glade"
        #setup the cmd that we will return
        self.gmailaddress = gmailaddress
        self.gmailpassword = gmailpassword

    def run(self):
        """This function will show the cmdDlg"""

        #load the dialog from the glade file
        self.wTree = gtk.glade.XML(self.gladefile, "googleDlg")
        
        #Get the actual dialog widget
        self.dlg = self.wTree.get_widget("googleDlg")
        #Get all of the Entry Widgets and set their text
        self.gmailaddress_entry = self.wTree.get_widget("gmailaddress_entry")
        self.gmailaddress_entry.set_text(self.gmailaddress)
        self.gmailpassword_entry = self.wTree.get_widget("gmailpassword_entry")
        self.gmailpassword_entry.set_text(self.gmailpassword)

        #run the dialog and store the response
        self.result = self.dlg.run()
        #get the value of the entry fields
        self.gmailaddress = self.gmailaddress_entry.get_text()
        self.gmailpassword = self.gmailpassword_entry.get_text()

        #we are done with the dialog, destory it
        self.dlg.destroy()

        #return the result and the cmd
        return self.result, self.gmailaddress,self.gmailpassword
    
    
class proxyDialog:
    """This class is used to show profileDlg"""

    def __init__(self, http_proxy = "", https_proxy = "",\
                 username_proxy = "", password_proxy = ""):
        """Initialize the class.
        """

        #setup the glade file
        self.gladefile = sys.path[0] + "/" + "erminig.glade"
        #setup the cmd that we will return
        self.http_proxy = http_proxy
        self.https_proxy = https_proxy
        self.username_proxy = username_proxy
        self.password_proxy = password_proxy

    def run(self):
        """This function will show the cmdDlg"""

        #load the dialog from the glade file
        self.wTree = gtk.glade.XML(self.gladefile, "proxyDlg")
        
        #Get the actual dialog widget
        self.dlg = self.wTree.get_widget("proxyDlg")
        #Get all of the Entry Widgets and set their text
        self.httpproxy_entry = self.wTree.get_widget("httpproxy_entry")
        self.httpproxy_entry.set_text(self.http_proxy)
        self.httpsproxy_entry = self.wTree.get_widget("httpsproxy_entry")
        self.httpsproxy_entry.set_text(self.https_proxy)
        self.userproxy_entry = self.wTree.get_widget("userproxy_entry")
        self.userproxy_entry.set_text(self.username_proxy)
        self.pwdproxy_entry = self.wTree.get_widget("pwdproxy_entry")
        self.pwdproxy_entry.set_text(self.password_proxy)


        #run the dialog and store the response
        self.result = self.dlg.run()
        #get the value of the entry fields
        self.http_proxy = self.httpproxy_entry.get_text()
        self.https_proxy = self.httpsproxy_entry.get_text()
        self.username_proxy = self.userproxy_entry.get_text()
        self.password_proxy = self.pwdproxy_entry.get_text()

        #we are done with the dialog, destory it
        self.dlg.destroy()

        #return the result and the cmd
        return self.result, self.http_proxy,self.https_proxy\
                              , self.username_proxy,self.password_proxy


class invalideventsDialog:
    """This class is used to show profileDlg"""

    def __init__(self, events = None):
        """Initialize the class.
        profile - a Profile object"""

        #setup the glade file
        self.gladefile = sys.path[0] + "/" + "erminig.glade"
        #setup the cmd that we will return
        self.events = events
        print ("Invalid events : ")
        print events

    def run(self):
        """This function will show the cmdDlg"""

        #load the dialog from the glade file
        self.wTree = gtk.glade.XML(self.gladefile, "invalideventsDlg")
        
        self.cTitle = 0
        self.sTitle = "Title"
        self.cStart = 1
        self.sStart = "Start date"
        
        #Get the actual dialog widget
        self.dlg = self.wTree.get_widget("invalideventsDlg")
        #Get all of the Entry Widgets and set their text
        self.events_treeview = self.wTree.get_widget("treeview3")
        #Add all of the List Columns to the cmdView
        self.AddEventListColumn(self.sTitle, self.cTitle)
        self.AddEventListColumn(self.sStart, self.cStart)

        #Create the listStore Model to use with the cmdView
        self.eventsList = gtk.ListStore(gobject.TYPE_STRING
                                        , gobject.TYPE_STRING)
        #Attache the model to the treeView
        self.events_treeview.set_model(self.eventsList)
        
        for event in self.events:
            self.eventsList.append([event[2], event[5]])

        #run the dialog and store the response
        self.result = self.dlg.run()

        #we are done with the dialog, destory it
        self.dlg.destroy()

        #return the result and the cmd
        return self.result
    
    
    def AddEventListColumn(self, name, columnId):
        """This function adds a column to the list view.
        First it create the gtk.TreeViewColumn and then set
        some needed properties"""

        column = gtk.TreeViewColumn(name, gtk.CellRendererText()
            , text=columnId)
        column.set_resizable(True)
        column.set_sort_column_id(columnId)
        self.events_treeview.append_column(column)
        
        
    

class Profile:
    """This class represents all the cmd information"""

    def __init__(self, name=""
                 , googlecalendarid="", googlecalendartitle=""
                 , gpecalendarid="", gpecalendartitle=""
                 , timezone="", gpeupdate="", googleupdate=""
                 , enabled=False, startdate = ""
                 , accesslevel = ""):

        self.name = name
        self.googlecalendartitle = googlecalendartitle
        self.googlecalendarid = googlecalendarid
        self.gpecalendartitle = gpecalendartitle
        self.gpecalendarid = gpecalendarid
        self.timezone = timezone
        self.gpeupdate = gpeupdate
        self.googleupdate = googleupdate
        self.enabled = enabled
        self.startdate = startdate
        self.accesslevel = accesslevel
                   

    def getList_cfg(self):
        """This function returns a list made up of the
        cmd information.  It is used to add a cmd to the
        cmdList easily"""
        return [self, self.name
                , self.googlecalendartitle
                , self.googlecalendarid
                , self.gpecalendartitle
                , self.gpecalendarid
                , self.timezone
                , self.gpeupdate
                , self.googleupdate
                , self.enabled
                , self.startdate
                , self.accesslevel]
        
        
    def getList_treeview(self):
        """This function returns a list made up of the
        cmd information.  It is used to add a cmd to the
        cmdList easily"""

        return [self, self.name
                , self.googlecalendartitle
                , self.googlecalendarid
                , self.gpecalendartitle
                , self.gpecalendarid
                , self.timezone
                , self.gpeupdate
                , self.googleupdate
                , self.enabled
                , self.icon()
                , self.lastupdate()]
        
        
    def icon(self):
        if (self.enabled == False):
            return gtk.STOCK_NO
        else:
            return gtk.STOCK_YES
            
    def lastupdate(self):
        printd("gpe update : " + self.gpeupdate)
        if ((self.gpeupdate == "") or 
             (self.gpeupdate == "0")):
            lastupdate = "Never"
        else:            
            lastupdate = datetime.datetime.fromtimestamp(float(self.gpeupdate))
        return lastupdate
        
        
class delDialog:
    """This class is used to show profileDlg"""

    def __init__(self, profile=None):
        """Initialize the class."""

        #setup the glade file
        self.gladefile = sys.path[0] + "/" + "erminig.glade"
        self.profile = profile


    def run(self):
        """This function will show the resultWindow"""

        #load the dialog from the glade file
        print "Loading result window"
        self.wTree = gtk.glade.XML(self.gladefile, "delDlg")
        
        self.profilelbl = self.wTree.get_widget("profile_lbl")
        self.profilelbl.set_text(self.profile.name)
        
        self.deldlg = self.wTree.get_widget("delDlg")
        self.result = self.deldlg.run()
        
        self.deldlg.destroy()
        
        return self.result

class Profiles():
    """This class holds the profiles of Erminig (i.e. the 
       GPE-Calendar <-> Google-Calendar relationships)"""

    def __init__(self, config):
        self.currentcfg = config.currentcfg
        self.init_profiles()

    def init_profiles(self):
        printd("Profiles list initialization...")
	    self.profileList = [];
	    self.read_config()

    def read_config(self):
	    for profile in self.currentcfg.profiles:
    		entry = self.currentcfg.get_profile(profile)
    		printd("cfg entry :")
    		printd(entry, False)
		    newProfile = Profile(entry[0], entry[1], entry[2], entry[3]
            	, entry[4], entry[5], entry[6]
        		, entry[7], entry[8], entry[9], entry[10])
    		self.profileList.append(newProfile.getList_treeview())
            
    def getProfile(self, profileName):
        for profile in self.profileList:
            if (profile[0].name == profileName):
                return profile

        return None

class GoogleAccess():
    def __init__(self, config):
        self.proxy_enabled = False
        self.config = config
        self.connectToGoogle()

    def connectToGoogle(self):
        #Configuring Google access object
        proxy_params = None
        if self.proxy_enabled:
            proxy_params = (self.config.currentcfg.http_proxy,
                                       self.config.currentcfg.https_proxy,
                                       self.config.currentcfg.user_proxy, 
                                       self.config.currentcfg.password_proxy)
        else:
           proxy_params = None

        printd("proxy parameters :")
        printd(proxy_params, False)

        try:
            self.google_access = google_service.GoogleObj()
            self.google_access.init_google_params(self.config.currentcfg.google_login, 
                                              self.config.currentcfg.google_password, proxy_params)
            self.google_access.load_google_calendars()
        except socket.gaierror:
            printd("Could not connect!")

    def reconnect(self):
        print "Reconnecting with new parameters..."
        self.connectToGoogle()
        
class GpeAccess():
    def __init__(self, commandLineMode):
        #Configuring Gpe access object
        self.gpe_access = gpe_service.GpeObj()
        if not self.gpe_access.init_gpe_params():
            if commandLineMode:
                print "Unable to open GPE Calendar file!"
            else:
                w = hildon.Window()
                message = "Unable to open GPE Calendar file!\n\n"
                message = message + "Please start GPE Calendar at least once before\n"
                message = message + "running Erminig."
                dialog = hildon.Note("information", (w, message, gtk.STOCK_DIALOG_ERROR))
                dialog.set_button_text("OK")
                dialog.run()
                dialog.destroy()
            exit(1)

        self.gpe_access.load_gpe_calendars()

class Config():
    def __init__(self):
	    self.currentcfg = erminigcfg.conf()
        self.currentcfg.load_configuration()

class ErminigText():
    def __init__(self, profiles, googleAccess, gpeAccess, config, useProxy):
        self.profiles = profiles
        self.google_access = googleAccess.google_access
        self.gpe_access = gpeAccess.gpe_access
        self.currentcfg = config.currentcfg
        self.useProxy = useProxy

    def checkConnectivity(self):
        proxy_params = None
        if self.useProxy: 
            proxy_params = (self.currentcfg.http_proxy,
                                   self.currentcfg.https_proxy,
                                   self.currentcfg.user_proxy, 
                                   self.currentcfg.password_proxy)

        # Check Google Connectivity:
        if not self.google_access.googleConnected:
            try:
                self.google_access.init_google_params(self.currentcfg.google_login, self.currentcfg.google_password, proxy_params)
            except socket.gaierror:
                print("Fatal: could not connect!")
                exit(1)

    def updateAll(self):
        self.checkConnectivity()
        MyProcessEvent=processevents.ProcessEventsObj(self.google_access, self.gpe_access, self.currentcfg)
	    for profile in self.profiles.profileList:
		    if (profile[0].enabled):
		    	print( "Updating: " + profile[0].name)
                result = MyProcessEvent.updateall(profile[0].name)
                if (result == 0):
                    printd("All tasks done")
                else:
                    printd("Aborted, invalid events detected")
#                    self.displayinvalidevents(result)

    def update(self, profilesToUpdate):
        self.checkConnectivity()
        MyProcessEvent=processevents.ProcessEventsObj(self.google_access, self.gpe_access, self.currentcfg)
        for p in profilesToUpdate:
            profileData = self.profiles.getProfile(p)
            if (profileData != None):
                if profileData[0].enabled:
    		    	print( "Updating: " + profileData[0].name)
                    result = MyProcessEvent.updateall(profileData[0].name)
                    if (result == 0):
                        print("OK")
                    else:
                        print("Errors while updating!")
            else:
                print "Profile \"" + p + "\" doesn't exist!"

def showVersion():
    message = "This is Erminig " + ERMINIG_VERSION + "\n\n"
    message = message + "Currently maintained by: Pascal Jermini\n"
    message = message + "Original Author: David Hautbois\n\n"
    message = message + "Homepage: http://erminig.garage.maemo.org\n"
    print message

def usage():
    print """
This is Erminig version """ + ERMINIG_VERSION + """

usage: """

    print "   " + sys.argv[0] + " [-h] [--help] [--all-profiles | --profiles=p1,p2,...] [--proxy]"
    print """
    where: 
        -h or --help         : show this help page
        --all-profiles       : synchronize all profiles in command line mode
        --profiles=p1,p2,... : synchronize in command line mode profiles 
                               named p1 and p2
        --proxy              : Enable proxy support (must be configured 
                               in GUI before using!)
    """
        


if __name__ == "__main__":
    commandLineMode = False;
    profilesToSync = "";
    syncAllProfiles = False
    useProxy = False

    try:
	    opts, args = getopt.getopt(sys.argv[1:], 'vh', ["profiles=", "all-profiles", "help", "proxy", "version"])
    except getopt.GetoptError, err:
        print str(err)
        usage()
	    exit(2)
    
    for o, a in opts:
	    if o == "--profiles":
		    commandLineMode = True
		    profilesToSync = a
	    elif o == "--all-profiles":
		    commandLineMode = True
            syncAllProfiles = True
        elif o == "-h" or o == "--help":
            usage()
            exit(0)
        elif o == "--proxy":
            useProxy = True
        elif o == "--version" or o == "-v":
            showVersion()
            exit(0)

    config = Config()
	profiles = Profiles(config)
    googleAccess = GoogleAccess(config)
    gpeAccess = GpeAccess(commandLineMode)

    if commandLineMode:
        erminigText = ErminigText(profiles, googleAccess, gpeAccess, config, useProxy)
        if (syncAllProfiles):
            erminigText.updateAll()
        else:
            erminigText.update(profilesToSync.split(','))
    else:
	    import gtk.glade
	    import gobject
	    x = erminigApp(profiles, googleAccess, gpeAccess, config, useProxy)
	    gtk.main()

