#!/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
# Something weird is happening when trying to send single messages ( = 160 )
maxmsgsize = 160 

def login( self ):    
            
    try:     
        # Get new eth codes
        usock = self.urlopen( self.Request( 'https://idn.ethz.ch/cgi-bin/sms/main.cgi', '', self.htmlHeaders ) )
        usockanswer = usock.read()
        
        self.code = re.search ('https://idn.ethz.ch/cgi-bin/sms/main.cgi/(.*)/_top', usockanswer ).group(1)
        logincode = re.search ('<input type\=\"submit\" name\=\"(.*?)\"', usockanswer ).group(1)
        passwdcode = re.search ('<input type\=\"password\" name\=\"(.*?)\"', usockanswer ).group(1)
        
        # Now log in
        loginURL = 'https://idn.ethz.ch/cgi-bin/sms/main.cgi/' + self.code + '/_top'
        loginValues = { '_username'    : self.eth[0].decode( 'utf-8' ).encode( 'iso-8859-1' ), 
                        passwdcode     : self.eth[1].decode('rot13').encode( 'iso-8859-1' ), 
                        '_login_page'  : '1',
                        logincode      : 'Login' 
                      }
        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.error_dialog( 'Failed to log on to the ETH server.\n'
                            + 'Error code - %d' % e.code )
        elif hasattr( e, 'reason' ):
            self.error_dialog( 'Failed to log on to the ETH server.\n'
                            + '%d' % e.reason[0] + ': ' + e.reason[1] + '.' )
        return False
    
    return True

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

def send( self ):
        
    sendURL = 'https://idn.ethz.ch/cgi-bin/sms/task1.fastpl/' + self.eth[0].decode( 'utf-8' ).encode( 'iso-8859-1' ) + '_' + self.code + '/_top'

    # Parse sender number to make sure
    usock = self.urlopen( self.Request( sendURL, '', self.htmlHeaders ) )
    usockanswer = usock.read()
    parsed_sender = '+41 ' + re.search('<option value=\"\+41 (.*)\"', usockanswer ).group(1)

    # 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 ETH online form)
            sendValues = { 'phone'                 : self.receivernumber.get_text(), 
                           'messagetext'           : message, 
                           'originator'            : 'phone',
                           'phoneoriginator'       : parsed_sender,
                           'send'                  : 'Send'
                         } 
        
            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():
            
            # 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['phone'] = self.sender
                sendValues['messagetext'] = 'Your message to ' + self.receivername + ' (' + self.receivernumber.get_text() + ') has been sent successfully through ETH sms service.'

                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 ETH server.\n'
                                                + 'Error code - %d' % e.code )
        elif hasattr( e, 'reason' ):
            self.error_dialog( 'Failed to send message from the ETH server.\n'
                                                + '%d' % e.reason[0] + ': ' + e.reason[1] + '.' )
    
