#!/usr/bin/python

import puff, string, os

class Bot:
    def __init__(self, botname, thepuff):
        self.botname= botname
        self.thepuff= thepuff
        self.thepuff.botGuard()
    def parse_help(self, args):
        self.output= self.output + "The help command is unimplemented, " +\
            "contrary to section 1b of the Bot Code.  Please bitch " + \
            "at the bot's author."
    def parse(self):
        objdict= self.__class__.__dict__
        self.output= ''
        self.message= self.thepuff.message
        while len(self.message) > 0:
            try:
                commandline= self.message[0]
                print commandline
                self.message= self.message[1:]
                args= string.split(commandline)
                cmd= args[0]
                if objdict.has_key("parse_" + cmd):
                    objdict["parse_" + cmd](self, args[1:])
                else: self.parseerror(cmd, args[1:])
            except IndexError:
                pass
    def parseerror(self, cmd, args):
        self.output= "unrecognized command: " + cmd + string.join(args)
        self.output= self.output + "\n\n"
        self.parse_help([])
    def report(self):
        print self.output
        if len(self.output) > 0:
            targets= self.thepuff.botTarget(self.botname)
            print targets
            gsend= "gsend -Ptautomaton/sender=" + self.botname
            if targets == None:
                return
            elif targets[0]:
                gsend= gsend + " " + targets[1]
            else:
                gsend= gsend + " -c '" + targets[1] + "'"
            print gsend
            fp= os.popen(gsend, "w")
            fp.write(self.output)
            fp.close()
    def run(self):
        if not self.thepuff.botGuard():
            print "parsing"
            self.parse()
            print "reporting"
            self.report()
