#!/usr/bin/env python

import sys
import logging
import gobject
import signal

import pymsn
from pymsn.profile import Presence
from pymsn.event import ClientEventInterface, ClientState, InviteEventInterface, ConversationEventInterface

logging.basicConfig(level=logging.DEBUG)


objcounter = 1


class ConversationEvents(ConversationEventInterface):
    def __init__(self, conv):
        global objcounter
        ConversationEventInterface.__init__(self, conv)
        self.count = objcounter
        objcounter += 1
        logging.debug("[%d] ConversationEvents created." % self.count)
    
    def on_conversation_user_joined(self, contact):
        logging.debug("[%d] User joined conversation: %s" % (self.count, contact.account))
    
    def on_conversation_user_left(self, contact):
        logging.debug("[%d] User left conversation: %s" % (self.count, contact.account))
    
    def on_conversation_message_received(self, sender, message):
        logging.debug("[%d] Got message from: %s" % (self.count, sender.account))

    def on_conversation_error(self, error_type, error):
        logging.error("[%d] %s -> %s" % (self.count, error_type, error))


class ClientEvents(ClientEventInterface, InviteEventInterface):
    def __init__(self, client):
        ClientEventInterface.__init__(self, client)
        InviteEventInterface.__init__(self, client)
        
    def on_client_state_changed(self, state):
        global mainloop
        if state == ClientState.CLOSED:
            logging.fatal("Connection closed.")
            mainloop.quit()
        
        elif state == ClientState.OPEN:
            self._client.profile.display_name = "PyMSN Test"
            self._client.profile.presence = Presence.ONLINE

    def on_client_error(self, error_type, error):
        logging.error("%s -> %s" % (error_type, error))
    
    def on_invite_conversation(self, conv):
        logging.info("Got conversation invite.")
        conv.handler = ConversationEvents(conv)
        for contact in conv.participants:
            conv.handler.on_conversation_user_joined(contact)


class Client(pymsn.Client):
    def __init__(self):
        pymsn.Client.__init__(self, ("messenger.hotmail.com", 1863))
        self.handler = ClientEvents(self)
        gobject.idle_add(self._connect)

    def _connect(self):
        global account, passwd
        self.login(account, passwd)
        return False


if __name__ == "__main__":
    if len(sys.argv) < 2:
        account = raw_input('Account: ')
    else:
        account = sys.argv[1]

    if len(sys.argv) < 3:
        passwd = getpass.getpass('Password: ')
    else:
        passwd = sys.argv[2]
    
    mainloop = gobject.MainLoop(is_running=True)
    
    def sig_cb():
        gobject.idle_add(mainloop.quit)
    signal.signal(signal.SIGTERM, sig_cb)
    signal.signal(signal.SIGINT, sig_cb)
    if hasattr(signal, "SIGBREAK"):
        signal.signal(signal.SIGBREAK, sig_cb)
    
    c = Client()
    
    while mainloop.is_running():
        try:
            mainloop.run()
        except KeyboardInterrupt:
            mainloop.quit()

