#!/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 = 160
            
def login( self ):    
        
    mainURL = 'http://www.schoolnet.ch/DE/HomeDE.htm'
           
    try:
        # Parse Monsterstring
        usock = self.urlopen( self.Request( mainURL, '', self.htmlHeaders ) )
        mainpage = usock.read()
        
        self.monsterstring = re.search( 'name=\"__VIEWSTATE\" value=\"(.*?)\" />', mainpage ).group( 1 )
        
        # Parse loginURL
        loginURL = re.search( '<base href=\"(.*?)\">', mainpage ).group( 1 )
        
        loginValues = { 'BotM:ucUser:ucUser2Col:txtUsename'  : self.schoolnet[0].decode( 'utf-8' ).encode( 'iso-8859-1' ),
                        'BotM:ucUser:ucUser2Col:txtPassword' : self.schoolnet[1].decode( 'rot13' ).encode( 'iso-8859-1' ),
                        
                        '__EVENTTARGET' : 'BotM:ucUser:ucUser2Col:cmdLogin',
                        '__EVENTARGUMENT' : '',
                        '__VIEWSTATE' : self.monsterstring
                      }
        
        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 )
        
    except IOError, e:
        if hasattr( e, 'code' ):
            self.error_dialog( 'Failed to log on to the schoolnet server.\n'
                            + 'Error code - %d' % e.code )
        elif hasattr( e, 'reason' ):
            self.error_dialog( 'Failed to log on to the schoolnet 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 ):

    message = self.msgbuffer.get_text( self.msgbuffer.get_start_iter(), self.msgbuffer.get_end_iter() )
    
    smsURL = 'http://www.schoolnet.ch/DE/FreundeInternet/SMS/';
    
    try:
        usock = self.urlopen( self.Request( smsURL, '', self.htmlHeaders ) )
        loginpage = usock.read()
 
        self.sendURL = re.search( '<base href=\"(.*?)\">', loginpage ).group( 1 )
        self.monsterstring = re.search( 'name=\"__VIEWSTATE\" value=\"(.*?)\" />', loginpage ).group( 1 )
        smsleft = int( re.search( '<TD align=\"right\" width=\"20\"><B>(.*?)</B></TD>', loginpage ).group( 1 ) )
        
        while message:

            if smsleft == 0:
                self.error_dialog( 'You don\'t have any credit points left to send new text messages.\n'
                                                + 'Please visit http://www.schoolnet.ch to earn more points.' )
                return False

            # If the message is larger the 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

            # Prepare the send values (defined by the swisscom online form)
            sendValues = {  '__EVENTTARGET' : 'Layout1:PresentationModeControlsContainer:_ctl1:_ctl0:_ctl0:cmdAnswer',
                            '__EVENTARGUMENT' : '',
                            '__VIEWSTATE' : self.monsterstring,
                            
                            'Layout1:PresentationModeControlsContainer:_ctl1:_ctl0:_ctl0:noSelec' : 'rbNo',
                            'Layout1:PresentationModeControlsContainer:_ctl1:_ctl0:_ctl0:txt_PhonePrefix' : self.receivernumber.get_text()[:3],
                            'Layout1:PresentationModeControlsContainer:_ctl1:_ctl0:_ctl0:txt_Phone' : self.receivernumber.get_text()[3:],
                            'Layout1:PresentationModeControlsContainer:_ctl1:_ctl0:_ctl0:txt_Message' : send_msg

                           }

            sendData = urllib.urlencode( sendValues )
             
            req = self.Request( self.sendURL, sendData, self.htmlHeaders )
            
            handle = self.urlopen( req )
            loginpage = handle.read()
            
            self.sendURL = re.search( '<base href=\"(.*?)\">', loginpage ).group( 1 )
            self.monsterstring = re.search( 'name=\"__VIEWSTATE\" value=\"(.*?)\" />', loginpage ).group( 1 )
            smsleft = int( re.search( '<TD align=\"right\" width=\"20\"><B>(.*?)</B></TD>', loginpage ).group( 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 = {  '__EVENTTARGET' : 'Layout1:PresentationModeControlsContainer:_ctl1:_ctl0:_ctl0:cmdAnswer',
                                '__EVENTARGUMENT' : '',
                                '__VIEWSTATE' : self.monsterstring,
                                
                                'Layout1:PresentationModeControlsContainer:_ctl1:_ctl0:_ctl0:noSelec' : 'rbNo',
                                'Layout1:PresentationModeControlsContainer:_ctl1:_ctl0:_ctl0:txt_PhonePrefix' : self.sender[:3],
                                'Layout1:PresentationModeControlsContainer:_ctl1:_ctl0:_ctl0:txt_Phone' : self.sender[3:],
                                'Layout1:PresentationModeControlsContainer:_ctl1:_ctl0:_ctl0:txt_Message' : 'Your message to ' + self.receivername + ' (' + self.receivernumber.get_text() + ') has been sent successfully through Schoolnet.',
                           }
            
                sendData = urllib.urlencode( sendValues )
                
                req = self.Request( self.sendURL, sendData, self.htmlHeaders )
                handle = self.urlopen( req )
                
                loginpage = handle.read()
                smsleft = int( re.search( '<TD align=\"right\" width=\"20\"><B>(.*?)</B></TD>', loginpage ).group( 1 ) )
        
        return smsleft
                
    except IOError, e:
        if hasattr( e, 'code' ):
            self.error_dialog( 'Failed to send message from the schoolnet server.\n'
                                                + 'Error code - %d' % e.code )
        elif hasattr( e, 'reason' ):
            self.error_dialog( 'Failed to send message from the schoolnet server.\n'
                                                + '%d' % e.reason[0] + ': ' + e.reason[1] + '.' )
    