#!/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 = 130

def login( self ):    
            
    try:     
        # Now log in
        loginURL = 'http://mymobile.sunrise.ch/portal/res/guest?paf_dm=full&paf_gear_id=100001&_DARGS=/portal/sunrise/login/html/LargeLogin.jsp'
        
        loginValues = { '_dyncharset' : 'iso-8859-1',
                        '_lg'    : self.sunrise[0].decode( 'utf-8' ).encode( 'iso-8859-1' ),
                        '_D:_lg' : ' ',
                        '/ch/sunrise/portal/mobile/login/LoginFormHandler.value.password' : self.sunrise[1].decode('rot13').encode( 'iso-8859-1' ), 
                        '_D:/ch/sunrise/portal/mobile/login/LoginFormHandler.value.password' : ' ',
                        '/ch/sunrise/portal/mobile/login/LoginFormHandler.cookie' : '1',
                        '_D:/ch/sunrise/portal/mobile/login/LoginFormHandler.cookie' : ' ',
                        '/ch/sunrise/portal/mobile/login/LoginFormHandler.nextUrl' : '/portal/res/guest?paf_dm=full&paf_gear_id=100001',
                        '_D:/ch/sunrise/portal/mobile/login/LoginFormHandler.nextUrl' : ' ',
                        '/ch/sunrise/portal/mobile/login/LoginFormHandler.errUrl' : '/portal/res/guest?paf_dm=full&paf_gear_id=100001',
                        '_D:/ch/sunrise/portal/mobile/login/LoginFormHandler.errUrl' : ' ',
                        '/ch/sunrise/portal/mobile/login/LoginFormHandler.guestUrl' : '/portal/res/guest',
                        '_D:/ch/sunrise/portal/mobile/login/LoginFormHandler.guestUrl' : ' ',
                        '/ch/sunrise/portal/mobile/login/LoginFormHandler.mysuccessUrl' : '',
                        '_D:/ch/sunrise/portal/mobile/login/LoginFormHandler.mysuccessUrl' : ' ',
                        '_D:loginSubmitImage' : ' ',
                        '_DARGS' : '/portal/sunrise/login/html/LargeLogin.jsp'
                      }
        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()
        
        smsleft = 0 #int( re.search('site=loadSms">(.*)&nbsp;gratis', handle.read()).group(1) )
        
    except IOError, e:
        if hasattr( e, 'code' ):
            self.error_dialog( 'Failed to log on to the Sunrise server.\n'
                            + 'Error code - %d' % e.code )
        elif hasattr( e, 'reason' ):
            self.error_dialog( 'Failed to log on to the Sunrise server.\n'
                            + '%d' % e.reason[0] + ': ' + e.reason[1] + '.' )
        return False
    
    return True, smsleft

def logout( self ):
    self.cj.clear()

def send( self ):
        
    sendURL = 'http://mymobile.sunrise.ch/portal/res/member?_DARGS=/portal/sunrise/sms/html/standard_sms.jsp'
    
    # Get message and convert it 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 Sunrise online form)
            sendValues = { '/ch/sunrise/portal/mobile/sms/SmsSendFormHandler.destination' : self.receivernumber.get_text(), 
                           'MESSAGE' : message, 
                           
                            '_dyncharset' : 'iso-8859-1',
                            '/ch/sunrise/portal/mobile/sms/SmsSendFormHandler.orgNumber' : 'msisdn',
                            '_D:/ch/sunrise/portal/mobile/sms/SmsSendFormHandler.orgNumber' : ' ',
                            '/ch/sunrise/portal/mobile/sms/SmsSendFormHandler.successUrl' : '/portal/res/member?paf_dm=full&paf_gear_id=500013',
                            '_D:/ch/sunrise/portal/mobile/sms/SmsSendFormHandler.successUrl' : ' ',
                            '/ch/sunrise/portal/mobile/sms/SmsSendFormHandler.buyUrl' : '/portal/res/member?paf_dm=full&paf_gear_id=500013&site=loadSms',
                            '_D:/ch/sunrise/portal/mobile/sms/SmsSendFormHandler.buyUrl' : ' ',
                            '_D:/ch/sunrise/portal/mobile/sms/SmsSendFormHandler.destination' : ' ',
                            'text_count' : '0', #TODO??
                            '_D:MESSAGE' : ' ',
                            
                            '/ch/sunrise/portal/mobile/sms/SmsSendFormHandler.update' : 'true',
                            '_D:/ch/sunrise/portal/mobile/sms/SmsSendFormHandler.update' : ' ',
                                       
                            '/ch/sunrise/portal/mobile/sms/SmsSendFormHandler.sendMessages' : ' ',
                            '_D:/ch/sunrise/portal/mobile/sms/SmsSendFormHandler.sendMessages' : ' ',
                            '/ch/sunrise/portal/mobile/sms/SmsSendFormHandler.formName' : 'SmsSend',
                            '_D:/ch/sunrise/portal/mobile/sms/SmsSendFormHandler.formName' : ' ',
                            '_DARGS' : '/portal/sunrise/sms/html/standard_sms.jsp'
                          }
        
            sendData = urllib.urlencode( sendValues )
        
            req = self.Request( sendURL, sendData, self.htmlHeaders )
            handle = self.urlopen( req )

            # 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():
            
            if ( self.sender == None ):
                self.error_dialog( 'Failed to send confirmation.\nPlease enter your mobile number in the preferences.\n' )
            else:
             	sendValues['/ch/sunrise/portal/mobile/sms/SmsSendFormHandler.destination'] = self.sender
             	sendValues['MESSAGE'] = 'Your message to ' + self.receivername + ' (' + self.receivernumber.get_text() + ') has been sent successfully through Orange CH.'

                sendData = urllib.urlencode( sendValues )
                
                req = self.Request( sendURL, sendData, self.htmlHeaders )
                handle = self.urlopen( req )
                
    except IOError, e:
        if hasattr( e, 'code' ):
            self.error_dialog( 'Failed to send message from the Sunrise server.\n'
                                                + 'Error code - %d' % e.code )
        elif hasattr( e, 'reason' ):
            self.error_dialog( 'Failed to send message from the Sunrise server.\n'
                                                + '%d' % e.reason[0] + ': ' + e.reason[1] + '.' )
    