#!/usr/bin/env python
# -*- coding: UTF8 -*-

# This file is part of PySms.
#
# PySms - A text messenger for various swiss providers
# Copyright (C) 2007 Andreas Maechler <amaechler@gmx.ch>
#
# PySms 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.
# 
# PySms 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 this program.  If not, see <http://www.gnu.org/licenses/>.


import sys
import os
import findcookielib

import gtk
import gtk.glade
import time 
import gobject
import string
import shutil
import csv
import pygtk
import ConfigParser

import orange, swisscom, eth, schoolnet
provider_list = ( 'Orange CH', 'Swisscom', 'N.ETHZ', 'Schoolnet' )

app_name      = 'PySms Text Messenger'
app_version   = 'unknown' # will be set in main() call
app_authors   = [ 'Andreas Maechler <amaechler@gmx.ch>' ]
app_copyright = 'Copyright (c) 2005-2007 Andreas Maechler'
app_website   = 'http://people.ee.ethz.ch/~maandrea/'

glade_dir    =  '/usr/share/pysms/'
icon_dir     =  '/usr/share/pysms/images/pysms_icon.png'
conf_dir     =   os.path.join( os.path.expanduser('~'), '.pysms' )
addressfile  =   os.path.join(conf_dir, 'addressbook.csv')
settingsfile =   os.path.join(conf_dir, 'settings')

settings     =   ConfigParser.ConfigParser()

class PySms:
    """This is the pySms application"""
        
    def __init__( self ):
        
        # Set the Glade file
        self.gladefile = os.path.join(glade_dir, 'pysms.glade')
        self.wTree = gtk.glade.XML( self.gladefile, "mainWindow" ) 
        
        # Create our dictionary and connect it
        dic = { "on_mainWindow_destroy" :                  self.quit, 
                "on_quit_activate" :                       self.quit, 
                "on_import_activate" :                     self.on_import_activate, 
                "on_export_activate" :                     self.on_export_activate, 
                "on_cut_activate" :                        self.on_cut_activate, 
                "on_copy_activate" :                       self.on_copy_activate, 
                "on_paste_activate" :                      self.on_paste_activate, 
                "on_preferences_activate" :                self.on_preferences_activate, 
                "on_information_activate" :                self.on_information_activate, 
                "on_about_activate" :                      self.on_about_activate, 
                "on_key_press" :                           self.on_key_press, 
                "on_button_clear_clicked" :                self.on_button_clear_clicked, 
                "on_button_send_clicked" :                 self.on_button_send_clicked, 
                "on_button_addressbook_toggled" :          self.on_button_addressbook_toggled, 
                "on_button_add_addressbook_clicked":       self.on_button_add_addressbook_clicked, 
                "on_button_delete_addressbook_clicked":    self.on_button_delete_addressbook_clicked, 
                "on_treeview_addressbook_row_activated" :  self.on_addressbook_row_activated     
              }
        self.wTree.signal_autoconnect( dic )

        # Define global variables
        self.app_name = app_name
        self.provider_list = provider_list

        self.provider = 0
        self.connected = -1
        self.savedTime = 0
        self.sentcounter = 0
        self.htmlHeaders = {'User-agent' : 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.6) Gecko/2007073113 Firefox/2.0.0.6 (Ubuntu-feisty)'}

        self.code = ''
        self.addresses = []
        self.smsleft = [ None ] * len( self.provider_list )

        # lastused, sender, addressbook, orange, swisscom, eth 

        # Check the user directory
        if not os.path.isdir( conf_dir ):
            os.mkdir( conf_dir )
        
        # Read the settings
        settings.read( settingsfile )
        
        # If the config file is non-existent, ConfigParser.read() simply
        # ignores it. So let's check if it has or sections or not
        if  settings.sections() == []:
            settings.add_section( 'Application' )
            settings.set( 'Application', 'last used', '0' )
            settings.set( 'Application', 'user number', '')
            settings.add_section( 'Providers' )
            settings.set( 'Providers', 'orange', ',' )
            settings.set( 'Providers', 'swisscom', ',' )
            settings.set( 'Providers', 'eth', ',' )
            settings.set( 'Providers', 'schoolnet', ',' )

            
        # Initialize cookie library
        ( self.cj, self.urlopen, self.Request ) = findcookielib.assign_cookielib()     

        # Connect to widgets
        self.main_window = self.wTree.get_widget( "mainWindow" )
        self.msg = self.wTree.get_widget( "textview_message" )
        self.msgbuffer = self.msg.get_buffer()
        self.num_chars = self.wTree.get_widget( "label_numchars" )
        self.num_sms = self.wTree.get_widget( "label_numsms" )
        self.statusbar = self.wTree.get_widget( "statusbar" )
        self.progressbar = self.wTree.get_widget( "progressbar" )
        self.receivernumber = self.wTree.get_widget( "entry_receiver" )
        self.affirmation = self.wTree.get_widget( "check_confirmation" )
        self.cb_main = self.wTree.get_widget( "combo_mainprovider" )
        self.addressbook = self.wTree.get_widget( "hbox_addressbook" )
        self.button_addressbook = self.wTree.get_widget( "button_addressbook" )
        
        # Initialize the main_provider combobox
        model = gtk.ListStore( str )
        for i in self.provider_list:
            model.append( [i] )
        self.cb_main.set_model( model )
        cell = gtk.CellRendererText()
        self.cb_main.pack_start( cell, True )
        self.cb_main.add_attribute( cell, 'text', 0 )
        self.cb_main.connect( 'changed', self.on_cb_main_changed )
        
        # Set combobox to last used provider
        self.cb_main.set_active( settings.getint( 'Application', 'last used' ) )
        
        # Initialize other widgets       
        self.update_statusbar( self.statusbar, 'Idle', 1 )
        self.on_key_press( self )
         
        # Initialize Clipboard
        self.clipb = gtk.Clipboard()
        
        # Initialize Addressbook
        self.addressview = self.wTree.get_widget( "treeview_addressbook" )
        self.add_addressbook_column( "Name", 0 )
        self.add_addressbook_column( "Phonenumber", 1 )
        
        self.addressbook_list = gtk.ListStore( str, str )
        self.addressview.set_model( self.addressbook_list )
        self.addressview.get_selection().set_mode(gtk.SELECTION_MULTIPLE)
        
        # Read the addressbook
        try:
            addresses = open( addressfile, 'r' )
            
            alist = addresses.read().split('\n')
            for i in range( len( alist ) - 1 ):
                self.addressbook_list.append( alist[i].split(', ') )
                
            addresses.close()
                
        except IOError:
            print "No Addresses found."
            
        
    def set_icon( self ):
        icon = self.get_icon('pysms')
        self.main_window.set_icon( icon )

    def get_icon( self, entry, size=24 ):
        path = icon_dir
        if path == None:
            pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, True, 8, size, size)
            pb.fill(0x00000000)
        else:
            try:
                pb = gtk.gdk.pixbuf_new_from_file_at_size(path, size, size)
            except:
                pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, True, 8, size, size)
                pb.fill(0x00000000)
        return pb
        
    def add_addressbook_column( self, title, columnId ):
        column = gtk.TreeViewColumn( title, gtk.CellRendererText(), text=columnId )
        column.set_resizable( True )        
        column.set_sort_column_id( columnId )
        self.addressview.append_column( column )
        
    def on_cb_main_changed( self, *args ):
        self.provider = self.cb_main.get_active()
        self.on_key_press( self )
    
    def update_progressbar( self, pbar, text, add_frac ):
        pbar.set_text( text )
        pbar.set_fraction( pbar.get_fraction() + add_frac )
        while gtk.events_pending(): gtk.main_iteration()

    def reset_progressbar( self, pbar ):
        pbar.set_text( '' )
        pbar.set_fraction( 0 )
        while gtk.events_pending(): gtk.main_iteration()

    def update_statusbar( self, sbar, text, context_id ):
        sbar.pop( context_id )
        sbar.push( context_id, text )

    def error_dialog( self, message ):
        err_dialog = gtk.MessageDialog( None, 
                                        gtk.DIALOG_DESTROY_WITH_PARENT, 
                                        type=gtk.MESSAGE_ERROR, 
                                        buttons=gtk.BUTTONS_CLOSE, 
                                        message_format=message )
        resp = err_dialog.run()
        if resp == gtk.RESPONSE_CLOSE: err_dialog.destroy()

        self.reset_progressbar( self.progressbar )

    def on_cut_activate( self, widget, *args ):
        self.msgbuffer.cut_clipboard( self.clipb, self.msg.get_editable() )

    def on_copy_activate( self, widget, *args ):
        self.msgbuffer.copy_clipboard( self.clipb )

    def on_paste_activate( self, widget, *args ):
        self.msgbuffer.paste_clipboard( self.clipb, None, self.msg.get_editable() )

    def on_preferences_activate( self, widget, *args ):
        prefDlg = PreferencesDialog()
        result = prefDlg.run()
    
    def on_information_activate( self, widget, *args ):
        infoDlg = InformationDialog()
        result = infoDlg.run( self.provider, self.connected, self.smsleft )
            
    def on_about_activate( self, widget, *args ):
        about = gtk.AboutDialog()
        about.set_name( app_name )
        about.set_version( app_version )
        about.set_comments( 'A simple tool for sending text messages.' )
        about.set_authors( app_authors )
        about.set_copyright( app_copyright )
        about.set_website( app_website )

        # text = open( os.path.join(basedir, 'COPYING') ).read()
        # about.set_license( text )
        
        try:
            about.set_logo( gtk.gdk.pixbuf_new_from_file_at_size( icon_dir, 164, 164))
        except:
            None
  
        about.connect ( "response", lambda d, r: d.destroy() )
        about.show()

    def on_key_press( self, widget, *args ) :
        
        if ( self.provider == 0 ):
            self.num_chars.set_text( repr( orange.maxmsgsize - ( self.msgbuffer.get_char_count() % orange.maxmsgsize ) ) )
            self.num_sms.set_text( repr( self.msgbuffer.get_char_count() / ( orange.maxmsgsize ) + 1 ) )
        elif ( self.provider == 1 ):
            self.num_chars.set_text( repr( swisscom.maxmsgsize - ( self.msgbuffer.get_char_count() % swisscom.maxmsgsize ) ) )
            self.num_sms.set_text( repr( self.msgbuffer.get_char_count() / ( swisscom.maxmsgsize ) + 1 ) )
        elif ( self.provider == 2 ):
            self.num_chars.set_text( repr( eth.maxmsgsize - ( self.msgbuffer.get_char_count() % eth.maxmsgsize ) ) )
            self.num_sms.set_text( repr( self.msgbuffer.get_char_count() / ( eth.maxmsgsize ) + 1 ) )
        elif ( self.provider == 3 ):
            self.num_chars.set_text( repr( schoolnet.maxmsgsize - ( self.msgbuffer.get_char_count() % schoolnet.maxmsgsize ) ) )
            self.num_sms.set_text( repr( self.msgbuffer.get_char_count() / ( schoolnet.maxmsgsize ) + 1 ) )
        else:
            # Standard text message size
            self.num_sms.set_text( repr( self.msgbuffer.get_char_count() / ( 160 ) + 1 ) )
            
    def on_button_clear_clicked( self, widget, *args ):
        self.msgbuffer.delete( self.msgbuffer.get_start_iter(), self.msgbuffer.get_end_iter() )
        
    def on_button_send_clicked( self, widget, *args ):
        # Not connected
        if ( self.connected == -1 ):
            ret_value = self.login()
        else:
            # Time-Out: Set to 20 Minutes
            if ( time.time() - self.savedTime ) > 1200:
                ret_value = self.reconnect()
            # Logged in to the wrong server
            elif self.connected != self.provider:
                ret_value = self.reconnect()
            else:
                ret_value = True

        if ret_value: self.send()

    def on_button_addressbook_toggled( self, widget, *args ):
        if self.button_addressbook.get_active():
            self.addressbook.show_all()
        else:
            self.addressbook.hide_all()
    
    def on_button_add_addressbook_clicked( self, widget, *args ):
        """Called when the user wants to add a address"""

        addDlg = AddDialog();        
        result, new_address = addDlg.run()
        
        if ( result == gtk.RESPONSE_OK ):
            """The user clicked Add"""
            self.addressbook_list.append( new_address )
            self.save_addressbook( self.addressview.get_model() )

    def on_addressbook_row_activated( self, widget, *args ):
        selection = self.addressview.get_selection()
        model, selected = selection.get_selected_rows()
        
        iters = [model.get_iter(path) for path in selected]
        numbers = [model.get_value( iter, 1 ) for iter in iters]
        self.receivernumber.set_text( ', '.join( numbers ) )
              
    def save_addressbook( self, model ):
        
        self.addresses = []
        model.foreach( self.save_rows )

        # Construct a csv string - ugly....
        address_string = ''
        for i in range( len( self.addresses ) ):
                if ( i/2 * 2 ) != i:
                    address_string += self.addresses[i-1] + ', ' + self.addresses[i] + '\n'
        return address_string
                
    
    def save_rows( self, model, path, iter ): 
        self.addresses += [model.get_value( iter, i ) for i in range( model.get_n_columns() )]

    def on_import_activate( self, widget, *args ):
                
        dialog = gtk.FileChooserDialog( "Import Addressbook...", None, 
                                       gtk.FILE_CHOOSER_ACTION_OPEN, 
                                       ( gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, 
                                        gtk.STOCK_SAVE, gtk.RESPONSE_OK ) )
        dialog.set_default_response( gtk.RESPONSE_OK )
        
        response = dialog.run()
        if response == gtk.RESPONSE_OK:
                        
            file = open( dialog.get_filename() )
            import_addresses =  file.read()
            
            for i in range( len( import_addresses('\n') ) - 1 ):
                self.addressbook_list.append( import_addresses.split('\n')[i].split(', ') )
                            
            file.close()
            dialog.destroy()
            
        elif response == gtk.RESPONSE_CANCEL:
            dialog.destroy()


    def on_export_activate( self, widget, *args ):
                
        dialog = gtk.FileChooserDialog( "Export Addressbook...", None, 
                                       gtk.FILE_CHOOSER_ACTION_SAVE, 
                                       ( gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, 
                                        gtk.STOCK_SAVE, gtk.RESPONSE_OK ) )
        dialog.set_default_response( gtk.RESPONSE_OK )
        
        response = dialog.run()
        if response == gtk.RESPONSE_OK:
                        
            logfile = open( dialog.get_filename(), 'w' )
            logfile.write( self.save_addressbook( self.addressview.get_model() ) )
            logfile.close()
            dialog.destroy()
            
        elif response == gtk.RESPONSE_CANCEL:
            dialog.destroy()
            return

        
    def on_button_delete_addressbook_clicked( self, widget, *args ):
        """Called when the user wants to delete a address"""
        selection = self.addressview.get_selection()
        model, selected = selection.get_selected_rows()

        iters = [model.get_iter(path) for path in selected]
        for iter in iters:
            model.remove(iter)
        self.save_addressbook( model )


    
    def reconnect( self ):
        self.logout()
        self.reset_progressbar( self.progressbar )
        if self.login(): return True
        else: return False
            
    def login( self ):
        self.savedTime = time.time()
        ret_value = False
        
        self.sentcounter = 0 
        global settings
        settings.set( 'Application', 'Last Used', str(self.cb_main.get_active()) )
        self.update_progressbar( self.progressbar, "Login in...", 0.33 )
            
        if ( self.provider == 0 ):
            self.orange = settings.get('Providers', 'Orange').split(',')
			
            if ( self.orange[0] == '' or self.orange[1] == '' ):
                self.error_dialog( 'You have not entered valid login values' )
                ret_value = False
            else:
                ret_value = orange.login( self ) 
            
            if ret_value: self.connected = 0
                 
        elif ( self.provider == 1 ):
            self.swisscom = settings.get('Providers', 'Swisscom').split(',')
            ret_value = swisscom.login( self )            
            if ret_value: self.connected = 1
                
        elif ( self.provider == 2 ):
            self.eth = settings.get('Providers', 'ETH').split(',')
            ret_value = eth.login( self )
            if ret_value: self.connected = 2
        
        elif ( self.provider == 3 ):
            self.schoolnet = settings.get('Providers', 'Schoolnet').split(',')
            ret_value = schoolnet.login( self )
            if ret_value: self.connected = 3

        if not ret_value:
            # Login failed somewhere
            self.connected = -1
            self.update_progressbar( self.progressbar, "Login failed", 0 )
            return False
        
        return True
                
                
    def logout( self ):
        self.connected = -1
        
        if ( self.provider == 0 ):
            orange.logout( self )
        elif ( self.provider == 1 ):
            swisscom.logout( self )
        elif ( self.provider == 2 ):
            eth.logout( self )
        elif (self.provider == 3):
            schoolnet.logout( self )
            
    def send( self ):
        self.update_progressbar( self.progressbar, 'Sending...', 0.33 )
        self.sender = settings.get( 'Application', 'User Number' )
        
        # Find the correspondending receiver name
        amod = self.addressview.get_model()
        for row in amod:
            if row[1] == self.receivernumber.get_text():
                self.receivername = row[0].decode( 'utf-8' ).encode( 'iso-8859-1' )
                break
            else:
                self.receivername = ''
        
        if ( self.provider == 0 ):
            self.smsleft[self.provider] = orange.send( self )
        elif ( self.provider == 1 ):
            self.smsleft[self.provider] = swisscom.send( self )
        elif ( self.provider == 2 ):
            self.smsleft[self.provider] = eth.send( self )
        elif (self.provider == 3):
            self.smsleft[self.provider] = schoolnet.send( self )
                
        self.update_statusbar( self.statusbar, 'Message sent', 1 )
        self.reset_progressbar( self.progressbar ) 

    def quit( self, *args ):
        # Save settings   
        sfile = open( settingsfile, 'w' )
        settings.write( sfile )
        sfile.close()

        addresses = open( addressfile, 'w' )
        addresses.write( self.save_addressbook( self.addressview.get_model() ) )
        addresses.close()
        
        print "Exit now..."
        gtk.main_quit()


class PreferencesDialog:
    """This class is used to show the preferences dialog"""

    def __init__( self ):
            
        # Setup the glade file
        self.gladefile = os.path.join(glade_dir, 'pysms.glade')
        self.app_name = app_name
        
    def run( self, ):
        """This function will show the prefDlg"""        
         
        # Load the dialog from the glade file            
        self.wTree = gtk.glade.XML( self.gladefile, "prefDlg" ) 
        self.dlg = self.wTree.get_widget( "prefDlg" )
        
        # Connect to widgets
        self.cb_pref = self.wTree.get_widget( "combo_prefprovider" )
        self.label_username = self.wTree.get_widget( "label_username" )
        self.entry_username = self.wTree.get_widget( "entry_username" )
        self.entry_password = self.wTree.get_widget( "entry_password" )
        self.entry_sender = self.wTree.get_widget( "entry_sender" )
        self.check_savepasswd = self.wTree.get_widget( "check_savepasswd" )
        
        # Initialize the provider ComboBox
        self.provider_list = provider_list        
        model = gtk.ListStore( str )
        for i in self.provider_list:
            model.append( [i] )
        self.cb_pref.set_model( model )
        cell = gtk.CellRendererText()
        self.cb_pref.pack_start( cell, True )
        self.cb_pref.add_attribute( cell, 'text', 0 )
        self.cb_pref.connect( 'changed', self.on_cb_pref_changed )

        # Get the item values from the settings file   
        self.last_provider = int( settings.get( 'Application', 'Last Used' ))
        self.sender = settings.get( 'Application', 'User Number' )
        self.orange = settings.get( 'Providers', 'Orange' ).split(',')
        self.swisscom = settings.get( 'Providers', 'Swisscom' ).split(',')
        self.eth = settings.get( 'Providers', 'ETH' ).split(',')
        self.schoolnet = settings.get( 'Providers', 'Schoolnet' ).split(',')
        
        if ( self.last_provider == 0 ):
            self.cb_pref.set_active( 0 )
            self.label_username.set_text( 'Username:' )
            if not ( self.orange[0] == None ):
                self.entry_username.set_text( self.orange[0] )
            if not ( self.orange[1] == None ):
                self.entry_password.set_text( self.orange[1].decode( 'rot13' ) )
            
        elif ( self.last_provider == 1 ):
            self.cb_pref.set_active( 1 )
            self.label_username.set_text( 'Mobile:' )
            if not ( self.swisscom[0] == None ):
                self.entry_username.set_text( self.swisscom[0] )
            if not ( self.swisscom[1] == None ):
                self.entry_password.set_text( self.swisscom[1].decode( 'rot13' ) )

        elif ( self.last_provider == 2 ):
            self.cb_pref.set_active( 2 )
            self.label_username.set_text( 'Username:' )
            if not ( self.eth[0] == None ):
                self.entry_username.set_text( self.eth[0] )
            if not ( self.eth[1] == None ):
                self.entry_password.set_text( self.eth[1].decode( 'rot13' ) )
        
        elif ( self.last_provider == 3 ):
            self.cb_pref.set_active( 3 )
            self.label_username.set_text( 'Nickname:' )
            if not ( self.schoolnet[0] == None ):
                self.entry_username.set_text( self.schoolnet[0] )
            if not ( self.schoolnet[1] == None ):
                self.entry_password.set_text( self.schoolnet[1].decode( 'rot13' ) )
                                
        if not ( self.sender == None ):
            self.entry_sender.set_text( self.sender )

        # Run the dialog and store the response
        self.result = self.dlg.run()
        
        if ( self.result == gtk.RESPONSE_OK ):
            """The user clicked the Save button"""

            active = self.cb_pref.get_active()
            if   ( active == 0 ): active = 'Orange'
            elif ( active == 1 ): active = 'Swisscom'
            elif ( active == 2 ): active = 'ETH'
            elif ( active == 3 ): active = 'Schoolnet'
            
            if self.check_savepasswd.get_active():
               settings.set( 'Providers', active, self.entry_username.get_text() + ',' + self.entry_password.get_text().encode( 'rot13' ) )
            else:
               settings.set( 'Providers', active, self.entry_username.get_text(), '' )
            
            settings.set( 'Application', 'User Number', self.entry_sender.get_text() )
               
        # We are done with the dialog, destroy it
        self.dlg.destroy()
        
        # return the result value and the entry values
        return self.result
    
    def on_cb_pref_changed( self, *args ):
        active = self.cb_pref.get_active()
        if ( active == 0 ):
            self.label_username.set_text( 'Username:' )
            if not ( self.orange[0] == None ):
                self.entry_username.set_text( self.orange[0] )
            if not ( self.orange[1] == None ):
                self.entry_password.set_text( self.orange[1].decode( 'rot13' ) )
        elif ( active == 1 ):
            self.label_username.set_text( 'Mobile:' )
            if not ( self.swisscom[0] == None ):
                self.entry_username.set_text( self.swisscom[0] )
            if not ( self.swisscom[1] == None ):
                self.entry_password.set_text( self.swisscom[1].decode( 'rot13' ) )
        elif ( active == 2 ):
            self.label_username.set_text( 'Username:' )
            if not ( self.eth[0] == None ):
                self.entry_username.set_text( self.eth[0] )
            if not ( self.eth[1] == None ):
                self.entry_password.set_text( self.eth[1].decode( 'rot13' ) )
        elif (active == 3):
            self.label_username.set_text( 'Nickname:' )
            if not ( self.schoolnet[0] == None ):
                self.entry_username.set_text( self.schoolnet[0] )
            if not ( self.schoolnet[1] == None ):
                self.entry_password.set_text( self.schoolnet[1].decode('rot13') )                                      


class InformationDialog:
    """This class is used to show the information dialog"""

    def __init__( self ):
            
        # Setup the glade file
        self.gladefile = os.path.join(glade_dir, 'pysms.glade')
        self.app_name = app_name
        
    def run( self, provider, connected, smsleft ):
        """This function will show the infoDlg"""        
        
        # Load the dialog from the glade file            
        self.wTree = gtk.glade.XML( self.gladefile, "infoDlg" ) 
        self.dlg = self.wTree.get_widget( "infoDlg" )
        
        # Connect to widgets
        self.currentprovider = self.wTree.get_widget( "label_currentprovider" )
        self.status = self.wTree.get_widget( "label_status" )
        self.smsleft = self.wTree.get_widget( "label_smsleft" )

        if ( provider == 0 ):
            self.currentprovider.set_text( "Orange CH" )
            self.smsleft.set_text( "Unlimited" )
            
        elif ( provider == 1 ):
            self.currentprovider.set_text( "Swisscom" )
            if smsleft[provider] == None:
                self.smsleft.set_text( "Unknown" )
            else:
                self.smsleft.set_text( str(smsleft[provider]) )
                
        elif ( provider == 2 ):
            self.currentprovider.set_text( "N.ETHZ" )
            self.smsleft.set_text( "Unknown" )
        
        elif (provider == 3):
            self.currentprovider.set_text("Schoolnet")
            if smsleft[provider] == None:
                self.smsleft.set_text( "Unknown" )
            else:
                self.smsleft.set_text( str(smsleft[provider]) )
                    
        # Set connection status
        if ( connected == -1 ):
            self.status.set_text( 'Not logged in.' )
        elif ( connected == 0 ):
            self.status.set_text( 'Logged in to Orange CH.' )
        elif ( connected == 1 ):
             self.status.set_text( 'Logged in to Swisscom.' )
        elif ( connected == 2 ):
             self.status.set_text( 'Logged in to ETH.' )
        elif (connected == 3):
             self.status.set_text( 'Logged in to Schoolnet.' )
        else:
             self.status.set_text( 'Unknown Status' )
 
        # Run the dialog and store the response
        self.result = self.dlg.run()

        # We are done with the dialog, destroy it
        self.dlg.destroy()
        
        # return the result value and the entry values
        return self.result
        
class AddDialog:
    """This class is used for the address book"""

    def __init__( self ):
            
        # Setup the glade file
        self.gladefile = os.path.join(glade_dir, 'pysms.glade')
        self.app_name = app_name
        
    def run( self ):
        """This function will show the addDlg"""        
         
        # Load the dialog from the glade file            
        self.wTree = gtk.glade.XML( self.gladefile, "addDlg" ) 
        self.dlg = self.wTree.get_widget( "addDlg" )
         
        # Connect to widgets
        self.name = self.wTree.get_widget( "entry_name" )
        self.number = self.wTree.get_widget( "entry_number" )

        # Run the dialog and store the response        
        self.result = self.dlg.run()
        
        # We are done with the dialog, destroy it
        self.dlg.destroy()
        
        # Return the result and the address
        return self.result, [ self.name.get_text(), self.number.get_text() ]


def main( __version__ = None ):
    global app_version
    
    app_version = __version__
    pysms = PySms()

    pysms.set_icon()
    gtk.main()

if __name__ == "__main__":
    print _("Please do not call pysms.py directly. Instead, call the pysms binary.")
    sys.exit( -1)
