import socket
import select
import os
import time
from MessageBuffer import *
import gobject

class GMessageIO:
    """
    Handles communication of messages to and from the server.
    It will use a message handler to send messages it receives.
    """

    def __init__(self, messageHandler):
        """
        attempt to connect to the server
        """        
        self.isConnected = False
        
        self.setMessageHandler(messageHandler)        
        self.messageBuffer = MessageBuffer()

    
    def connect(self, host, port):
        """
        attempts to connect via TCP to host and port
        if successful, it will start our listening thread
        """
        self.host = host
        self.port = port
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        self.socket.connect( (host, port) )
        
        self.isConnected = True
        
        gobject.io_add_watch(self.socket, gobject.IO_IN, self.dataInput)
    
    def sendMessage(self, message):
        """
        sends a serialized version of the message over the socket
        """        
        if self.isConnected:
            #print "Send Message:", self.socket, message.address
            
            self.socket.send(message.getBinary())            

    def setMessageHandler(self, messageHandler):
        """
        the method our class will call when it has a full message to send
        """
        self.messageHandler = messageHandler

    def stopListening(self):
        """
        inform the select() that we want to stop listening
        """
        pass

    def readSocket(self):
        print "readSocket"
        data = self.socket.recv(16384)
        print "=========data Input", len(data)
        print data
        
        # check to see if error occurs?
        dataLen = len( data )
                
        remainingData = data
        
        parsing = 1

        while parsing and len(remainingData) > 0:
            remainingData = self.messageBuffer.processUntilNextMessage(remainingData)
        
            if self.messageBuffer.hasCompleteMessage():
                self.messageHandler( self.messageBuffer.getMessage() )
                
                self.messageBuffer.reset()
                
            else:
                parsing = 0
                    
        return dataLen
            
    def dataInput(self, source, condition, userData = None):
        lenRead = self.readSocket()
        
        return True