#!/usr/bin/python2.5

# vim:ts=4:et

import gpe_service
from erminigcfg import ErminigCfg
from google_service import GoogleConnector
import processevents

import sys
import os
import datetime
import getopt
import hildon
import string

import gtkexcepthook

from utils import *

ERMINIG_VERSION="3.0.3-3"

class erminigApp():
    """Erminig Application"""

    def __init__(self, profiles, gpeAccess, config):
        self.profiles = profiles
        self.google_access = GoogleConnector()
        self.gpe_access = gpeAccess.gpe_access
        self.currentcfg = config

        #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.app.__init__()
        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.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.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.sName = "Name"
        self.sEnabled = "Enabled"
        self.sLastUpdate = "Last update"

        self.cIcon = 0
        self.cName = 1
        self.cLastUpdate = 2

        #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(str, str, str)
        #Attache the model to the treeView
        self.profileView.set_model(self.profileList)
        self.updateProfilesList()

    def connectToGoogle(self):
        res = True
        connection = self.google_access.init_google_params(self.currentcfg)
        if not connection[0]:
            guimessage(connection[1], self.mainwindow, gtk.STOCK_DIALOG_ERROR)
            res = False

        return res


    def on_Quit(self, widget):
        """Called when the application is going to quit"""
        gtk.main_quit()

    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"
        guimessage(message, self.mainwindow, gtk.STOCK_DIALOG_INFO)

    def updateProfilesList(self):
        # Populate the profile list...
        self.profileList.clear()
        for p in self.profiles.get_profileList():
                treeview = []
                if p.is_enabled():
                    treeview.append(gtk.STOCK_YES)
                else:
                    treeview.append(gtk.STOCK_NO)
                treeview.append(p.get_name())
                treeview.append(p.get_lastupdate())

                self.profileList.append(treeview)
        
    def debugmode(self, msg):
        if (not self.currentcfg.get_debug_status()):
            self.currentcfg.set_debug_status(True)
            #Write to log file
            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.currentcfg.set_debug_status(False)
            sys.stdout = self.saveout
            sys.stderr = self.saveerr
            self.fsock.close()
            
            
    def proxymode(self, msg):
        self.currentcfg.flip_proxy_status()

#        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_UpdateProfile(self, widget):
        """Called when  the user want to update a profile"""
        # Get the selection iter
        model, sel_ptr = self.profileView.get_selection().get_selected()
        
        if (sel_ptr):
            """There is a selection, so now get the the value at column
            self.cCmdObject, the Cmd Object"""
            profile_name = model.get_value(sel_ptr, self.cName)
            profile = self.profiles.getProfile(profile_name)
            if profile.is_enabled():
                if self.connectToGoogle():
                    # Updating the profile (todo)
                    MyProcessEvent=processevents.ProcessEventsObj(self.google_access, 
                            self.gpe_access, self.currentcfg)
                    result = MyProcessEvent.updateall(profile.name, self.window, 
                            self.progressbar)

                    self.progressbar.set_fraction(0.0)
                    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)

        # Re-read config to update timestamp (a bit ugly...to be changed!)
        self.profiles.init_profiles()
        self.updateProfilesList()
    
    
    def on_UpdateAll(self, widget):
        """Update all profiles"""

        if not self.connectToGoogle():
            return

        MyProcessEvent=processevents.ProcessEventsObj(self.google_access, 
                self.gpe_access, self.currentcfg)
        for profile in self.profiles.get_profileList():
            if profile.is_enabled():
                print "on_UpdateAll : Profile to update : " + profile.get_name()
                result = MyProcessEvent.updateall(profile.get_name(), 
                        self.window, self.progressbar)
                if (result == 0):
                    print("All tasks done")
                else:
                    print ("Aborted, invalid events detected")
                    self.displayinvalidevents(result)
        self.progressbar.set_fraction(0.0)
        self.progressbar.set_text("Success update !")    

        # Re-read config to update timestamp (a bit ugly...to be changed!)
        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
        model, sel_ptr = self.profileView.get_selection().get_selected()

        if (sel_ptr):
            profile_name = model.get_value(sel_ptr, self.cName)
            profile = self.profiles.getFullProfile(profile_name)
            
            # Create the profile dialog, based off of the current selection

            profileDlg = profileDialog(self.profiles.get_profileNames(), profile, 
                    None, 
                    self.gpe_access.gpecalendars, True)

            newProfile = profileDlg.run()

            if newProfile:
                self.profiles.save_profile(newProfile)
                self.updateProfilesList()
                
    def edit_google_params(self, widget):
        """Called when the user wants to edit google parameters"""

        googleDlg = googleDialog(self.currentcfg.get_google_params())
        result, google_params = googleDlg.run()

        if result == gtk.RESPONSE_OK:
            self.currentcfg.write_google_parameters(google_params)
                   
    
    def edit_proxy_params(self, widget):
        """Called when the user wants to edit proxy parameters"""

        proxyDlg = proxyDialog(self.currentcfg.get_proxy_params())
        result, proxy_params = proxyDlg.run()
         
        if result == gtk.RESPONSE_OK:
            self.currentcfg.write_proxy_parameters(proxy_params)

    def OnAddProfile(self, widget):
        """Called when the use wants to add a cmd"""
        # Create the dialog, show it, and store the results
        if not self.connectToGoogle():
            return

        # create an empty profile:
        newProfile = {'name': '', 'googlecalendartitle': '', 
            'googlecalendarid': '', 'gpecalendartitle': '', 
            'gpecalendarid': '', 'timezone_name': '', 
            'gpeupdate': '', 'googleupdate': '', 'enabled': True, 
            'startdate': '', 'accesslevel': ''}
        profileDlg = profileDialog(self.profiles.get_profileNames(), newProfile, 
                    self.google_access.get_google_calendars(),
                    self.gpe_access.gpecalendars)

        newProfile = profileDlg.run()

        if newProfile:
            self.profiles.save_profile(newProfile)
            self.updateProfilesList()
            
    def OnDelProfile(self, widget):
        # Get the selected item
        model, sel_ptr = self.profileView.get_selection().get_selected()
        
        if (sel_ptr):
            """There is a selection"""
            profile_name = model.get_value(sel_ptr, self.cName)
            profile = self.profiles.getProfile(profile_name)

            message = "Delete the profile \"" + profile_name + "\" ?"
            dialog = hildon.Note("confirmation", (self.mainwindow, message, 
                gtk.STOCK_DIALOG_QUESTION))
            dialog.set_button_texts("Yes", "No")
            response = dialog.run() 
            dialog.destroy()

            if response == gtk.RESPONSE_OK:
                self.profileList.remove(sel_ptr)
                self.currentcfg.delete_profile(profile_name)
                self.profiles.remove_profile(profile_name)
                
                
    def displayinvalidevents(self, result):
        
        invalideventsDlg = invalideventsDialog(result);
        result = invalideventsDlg.run()

    def refresh_widgets(self):
        
        self.addprofile_btn = self.wTree.get_widget("tbAddProfile")
        self.updateprofile_btn = self.wTree.get_widget("tbUpdateProfile")

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

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

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

    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
        self.dateeditor = hildon.DateEditor()
        self.empty_zone = self.wTree.get_widget("table2")
        self.empty_zone.attach(self.dateeditor, 1, 2, 5, 6, gtk.EXPAND, 
                gtk.EXPAND)
        if self.profile['startdate'] <> '':
            # mbof...alternative please?
            date = string.split(self.profile['startdate'], '-')
            self.dateeditor.set_date(int(date[0]), int(date[1]), int(date[2]))

        self.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)

        # If editing, just show the current Google calendar, since
        # we cannot modify this attribute, no sense fetching them all...
        if self.edit:
                liststore.append([self.profile['googlecalendartitle']])
        else:
            for calendar in self.googlecalendars:
                liststore.append([calendar[1]])

        self.googlecalendar_combo.set_model(liststore)    
        
        model = self.googlecalendar_combo.get_model()
        if self.edit:
            i = 0
            for item in model:
                if item[0] == self.profile['googlecalendartitle']:
                    self.googlecalendar_combo.set_active(i)
                    break
                i = i + 1
        else:
            self.googlecalendar_combo.set_active(0)

        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)
        for calendar in self.gpecalendars:
            liststore.append([calendar[1]])
        self.gpecalendar_combo.set_model(liststore)    
        
        model = self.gpecalendar_combo.get_model()
        if self.edit:
            i = 0
            for item in model:
                if item[0] == self.profile['gpecalendartitle']:
                    self.gpecalendar_combo.set_active(i)
                    break
                i = i + 1
        else:
            self.gpecalendar_combo.set_active(0)
        
        self.enabled_cb = self.wTree.get_widget("enabled_cb")
        self.enabled_cb.set_active(self.profile['enabled'])
        
        self.readonly_cb  = self.wTree.get_widget("readonly_cb")
        if (self.profile['accesslevel'] == "read"): 
            self.readonly_cb.set_active(True)
        
        if (self.edit):
            self.gpecalendar_combo.set_sensitive(False)
            self.googlecalendar_combo.set_sensitive(False)
            self.dateeditor.set_sensitive(False)
            self.name_entry.set_sensitive(False)
            self.readonly_cb.set_sensitive(False)

        #run the dialog and store the response

        ret =  self.waitForAnswer()
        self.dlg.destroy()
        return ret

    def waitForAnswer(self):

        ret = None
        dataIsOk = False

        while not dataIsOk:
            result = self.dlg.run()

            if result == gtk.RESPONSE_OK:
                if self.edit:
                    self.profile['enabled'] = self.enabled_cb.get_active()
                    ret = self.profile
	                #we are done with the dialog, destroy it
	                self.dlg.destroy()
	                #return the result and the cmd
	                dataIsOk = True
                else:
	                #get the value of the entry fields
	                self.profile['name'] = self.name_entry.get_text().strip()
	                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]
	    
	                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])
	    
	                self.profile['timezone_name'] = \
	                    [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" % \
	                    (self.dateeditor.get_year(), self.dateeditor.get_month(), 
	                            self.dateeditor.get_day())
	    
	                if (self.readonly_cb.get_active()):
	                    self.profile['accesslevel'] = "read"
	
	                # check if all fields are correctly filled:
	                if self.profile['name'] == '':
	                    message = "The profile name must be provided!"
	                    guimessage(message, self.dlg, gtk.STOCK_DIALOG_ERROR)
	                # or if a profile with the same name exists:
	                elif ((not self.edit) and 
	                        (self.profileList.count(self.profile['name']) > 0)):
	                    message = "A profile named \"" + self.profile['name'] + "\" already exist!\n Please choose another name."
	                    guimessage(message, self.dlg, gtk.STOCK_DIALOG_ERROR)
	                else:
	                   ret = self.profile
	                   #we are done with the dialog, destroy it
	                   self.dlg.destroy()
	                   #return the result and the cmd
	                   dataIsOk = True
            else:
                dataIsOk = True

        return ret
    

class googleDialog:

    def __init__(self, google_params):
        #setup the glade file
        self.gladefile = sys.path[0] + "/" + "erminig.glade"
        #setup the cmd that we will return
        self.google_params = google_params

    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.google_params['user'])
        self.gmailpassword_entry = self.wTree.get_widget("gmailpassword_entry")
        self.gmailpassword_entry.set_text(self.google_params['password'])

        #run the dialog and store the response
        self.result = self.dlg.run()
        #get the value of the entry fields
        self.google_params['user'] = self.gmailaddress_entry.get_text()
        self.google_params['password'] = 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.google_params
    
    
class proxyDialog:

    def __init__(self, proxy_params):
        #setup the glade file
        self.gladefile = sys.path[0] + "/" + "erminig.glade"
        self.proxy_params = proxy_params

    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.proxy_params['http_proxy'])
        self.httpsproxy_entry = self.wTree.get_widget("httpsproxy_entry")
        self.httpsproxy_entry.set_text(self.proxy_params['https_proxy'])
        self.userproxy_entry = self.wTree.get_widget("userproxy_entry")
        self.userproxy_entry.set_text(self.proxy_params['user_proxy'])
        self.pwdproxy_entry = self.wTree.get_widget("pwdproxy_entry")
        self.pwdproxy_entry.set_text(self.proxy_params['password_proxy'])

        #run the dialog and store the response
        self.result = self.dlg.run()
        #get the value of the entry fields
        self.proxy_params['http_proxy'] = self.httpproxy_entry.get_text()
        self.proxy_params['https_proxy'] = self.httpsproxy_entry.get_text()
        self.proxy_params['user_proxy'] = self.userproxy_entry.get_text()
        self.proxy_params['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.proxy_params


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:
    def __init__(self, profileInfos):
        self.name = profileInfos['name']
        self.enabled = profileInfos['enabled']
        self.lastupdate = profileInfos['gpeupdate']

    def get_name(self):
        return self.name

    def is_enabled(self):
        return self.enabled
    
    def get_lastupdate(self):
        lastupdate = "Never"
        if (not ((self.lastupdate == "") or (self.lastupdate == "0"))):
            lastupdate = datetime.datetime.fromtimestamp(float(self.lastupdate))

        return lastupdate

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

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

    def init_profiles(self):
	    self.profileList = [];
	    self.read_config()

    def get_profileList(self):
        return self.profileList

    def get_profileNames(self):
        return self.currentcfg.profiles

    def read_config(self):
	    for profile in self.currentcfg.profiles:
            entry = self.currentcfg.get_profile_info(profile)
            self.profileList.append(Profile(entry))
            
    def getProfile(self, profileName):
        ret = None
        for profile in self.profileList:
            if (profile.get_name() == profileName):
                ret = profile
                break

        return ret

    def getFullProfile(self, profileName):
        return self.currentcfg.get_profile(profileName)

    def remove_profile(self, profile_name):
        for p in self.profileList:
            if p.get_name() == profile_name: 
                self.profileList.remove(p)
                break

    def save_profile(self, profile):
        self.currentcfg.write_profile(profile)
        # Re-read profiles
        self.init_profiles()

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:
                import gtk
                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."
                guimessage(message, w, gtk.STOCK_DIALOG_ERROR)
            exit(1)

        self.gpe_access.load_gpe_calendars()

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

        self.connectToGoogle()

    def connectToGoogle(self):
        connection = self.google_access.init_google_params(self.config)
        if not connection[0]:
            print connection[1]
            exit(1)


    def updateAll(self):
        MyProcessEvent=processevents.ProcessEventsObj(self.google_access, 
                self.gpe_access, self.config)
	    for profile in self.profiles.profileList:
		    if profile.is_enabled():
		    	print( "Updating: " + profile.get_name())
                result = MyProcessEvent.updateall(profile.get_name(), 
                        textMode=True, 
                        alwaysDelete=self.config.get_confirm_gdeletions())
                if (result == 0):
                    printd("All tasks done")
                else:
                    printd("Aborted, invalid events detected")

    def update(self, profilesToUpdate):
        MyProcessEvent=processevents.ProcessEventsObj(self.google_access, 
                self.gpe_access, self.config)
        for p in profilesToUpdate:
            profileData = self.profiles.getProfile(p)
            if (profileData != None):
                if profileData.is_enabled():
    		    	print( "Updating: " + profileData.get_name())
                    result = MyProcessEvent.updateall(profileData.get_name(), 
                            textMode=True, 
                            alwaysDelete=self.config.get_confirm_gdeletions())
                    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 "                       [--confirm-google-deletions]"
    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!)
        --confirm-google-deletions : Always allow the deletion of events in
                                     Google Calendar (only for text-mode)
    """
        


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

    config = ErminigCfg()

    try:
	    opts, args = getopt.getopt(sys.argv[1:], 'vh', ["profiles=", "all-profiles", "help", "proxy", "version",
                "confirm-google-deletions"])
    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 == "--confirm-google-deletions":
            config.set_confirm_gdeletions(True)
        elif o == "-h" or o == "--help":
            usage()
            exit(0)
        elif o == "--proxy":
            config.set_proxy_status(True)
        elif o == "--version" or o == "-v":
            showVersion()
            exit(0)

	profiles = Profiles(config)
    gpeAccess = GpeAccess(commandLineMode)

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

