#!/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 re
import urllib

# Global variables
maxmsgsize = 142
counterlimit = 10

def login( self ):

    try:
        # Get new orange code
        usock = self.urlopen( self.Request( 'http://www.orange.ch/footer/login', '', self.htmlHeaders ) )
        self.code = re.search( 'www.orange.ch/footer/login/loginForm\?ts=(.*?)\" method', usock.read() ).group( 1 )

        # Now log in
        loginURL = 'https://www.orange.ch/footer/login/loginForm?ts=' + self.code

        loginValues = { 'username' : self.orange[0].decode( 'utf-8' ).encode( 'iso-8859-1' ),
                        'password' : self.orange[1].decode('rot13').encode( 'iso-8859-1' ),
                        'wui_target_id' : 'loginButton',
                        'wui_event_id'  : 'onclick'
                      }
        loginData = urllib.urlencode( loginValues )

        # Create a request object
        req = self.Request( loginURL, loginData, self.htmlHeaders )

        # Open it to return a handle on the url
        handle = self.urlopen( req )
        #print handle.read()

    except IOError, e:
        if hasattr( e, 'code' ):
            self.errorDialog( 'Failed to log on to the orange server.\n'
                            + 'Error code - %d' % e.code )
        elif hasattr( e, 'reason' ):
            self.error_dialog( 'Failed to log on to the orange server.\n'
                            + '%d' % e.reason[0] + ': ' + e.reason[1] + '.' )
        return False

    return True

def logout( self ):
    self.cj.clear()
    self.sentcounter = 0

def send( self ):

    sendURL = 'https://www.orange.ch/sms/smsForm?ts=' + self.code

    # Get message and convert into the correct charset
    message = self.msgbuffer.get_text( self.msgbuffer.get_start_iter(), self.msgbuffer.get_end_iter() )
    message = message.decode( 'utf-8' ).encode( 'iso-8859-1' )

    try:
        while message: # this means while message != ''

            # If the message is larger then the max. size message we can send
            if len( message ) > maxmsgsize:
                # Search for a space to split the message nicely
                for i in range( maxmsgsize ):
                    if message[maxmsgsize - i] == ' ':
                        break

                # If there was no whitespace to split the message, just send the max. message
                if ( i == maxmsgsize-1 ):
                    send_msg = message[:maxmsgsize-1]
                    message = message[maxmsgsize:]
                # Else split the message at the found whitespace
                else:
                    send_msg = message[:maxmsgsize - i]
                    message = message[maxmsgsize - i + 1:]

            else:
                send_msg = message
                message = ''

            # Prepare the send values (defined by the orange online form)
            sendValues = { 'destinationNumberInput' : self.receivernumber.get_text(),
                           'messageInput'           : send_msg,
                           'signatureInput'         : '',
                           'wui_event_id'           : 'onclick',
                           'wui_target_id'          : 'sendButton' }

            sendData = urllib.urlencode( sendValues )


            # Check if we still can send text messages
            if not ( self.sentcounter < counterlimit ):
                self.reconnect()

            req = self.Request( sendURL, sendData, self.htmlHeaders )
            handle = self.urlopen( req )

            self.sentcounter =  self.sentcounter + 1

            # Check if we are done
            if send_msg == message:
                break

        # If the user would like an affirmation for the sent message
        if self.affirmation.get_active():

            # Check if the user has entered a sender number
            if ( self.sender == None ):
                self.error_dialog( 'Failed to send confirmation.\nPlease enter your mobile number in the preferences.\n' )
            else:
                sendValues['destinationNumberInput'] = self.sender
                sendValues['messageInput'] = 'Your message to ' + self.receivername + ' (' + self.receivernumber.get_text() + ') has been sent successfully through Orange CH.'

                sendData = urllib.urlencode( sendValues )

                # Check if we still can send text messages
                if not ( self.sentcounter < counterlimit ):
                    self.reconnect()

                req = self.Request( sendURL, sendData, self.htmlHeaders )
                handle = self.urlopen( req )
                self.sentcounter =  self.sentcounter + 1

    except IOError, e:
        if hasattr( e, 'code' ):
            self.error_dialog( 'Failed to send message from the orange server.\n'
                                                + 'Error code - %d' % e.code )
        elif hasattr( e, 'reason' ):
            self.error_dialog( 'Failed to send message from the orange server.\n'
                                                + '%d' % e.reason[0] + ': ' + e.reason[1] + '.' )
