"""
This code is released under the MIT license. The full package
is available at http://achievewith.us/svn/public/examples/xmppclients/
"""

import os
import sys
import time
import threading
import random

try:
    import conf
except ImportError:
    print """You need a configuration file.  Take conf.py.example,
copy it to conf.py, and edit it to suit your environment"""
    sys.exit(-1)

conf.quit = False
    
class JabberBot(object):
    def __init__(self, username, password, server, users):
        self.username = username
        self.password = password
        self.server = server
        self.users = users

    def sendMessage(self, user, message):
        print "To: %s\n%s\n\n" % (user, message)

    def processMessage(self, user, message):
        # Here we do some application specific thing with the incoming message.
        # Save it to a database?
        # Take an action on the system?
        # Since this is a demo, we'll just print it to the console
        # and thank the user.
        print "[%s] %s" % (user, message)
        self.send(user, "Thanks!")

        if message.lower().find("quit") != -1:
            conf.quit = True
            sys.exit(0)

def sending_thread(bot):
    print "Sending thread is active"
    while not conf.quit:
        time.sleep(10)        
        user = bot.users[random.randint(0, len(bot.users) -1)]
        message = conf.messages[random.randint(0, len(conf.messages) -1)]
        bot.send(user, message)
    print "Sender dying"

def run_bot(botclass):
    bot = botclass(username=conf.username,
                   password=conf.password,
                   server=conf.server,
                   users=conf.users)
    
    from threading import Thread    
    sender = Thread(target=sending_thread, args=[bot])
    sender.start()

if __name__ == "__main__":
    print """This program is pretty lame all by itself.
You may want to look into the subclasses."""