import asyncore, socket
from Queue import Queue

# Major and minor version of this server.
MAJOR_VERSION = 1
MINOR_VERSION = 0

class AsyncBase(asyncore.dispatcher):
    """
    Base class of the asynchronous connection of the chat system. The server and
    the client will use this base class to implement their connection.
    """

    def __init__(self):
        self.send_queue = Queue()
        self.send_buffer = ''

        # Connection/chat event callbacks
        self.event_list = { }

    def init_loop(self):
        """
        Initialise the asyncore loop (blocking). Set a timeout of 0.1 seconds
        and use poll() when available.
        """
        asyncore.loop(.1, True)

    def debug_log(self, msg):
        if 'debug' in self.event_list:
            self.event_list['debug'](self, msg)
        else:
            print msg

    def send_raw(self, cmd):
        """
        Send raw command to the chat server.
        """
        self.send_queue.put(cmd)

    def handle_write(self):
        if not self.send_buffer:
            self.send_buffer = self.send_queue.get()
            self.debug_log('> %s' % self.send_buffer)
            self.send_buffer += '\r\n'
        sent = self.send(self.send_buffer)
        self.send_buffer = self.send_buffer[sent:]

    def writable(self):
        return not self.send_queue.empty() or len(self.send_buffer)

