from twisted.words.protocols import irc
import logging

log = logging.getLogger("IRCBot")

NOT_IMPLEMENTED="Sorry mate, this command isn't implemented yet!"

guest_commands = {'HELP': None,
                  'EPHEM': ['get ephemerides of an object with ephem <name>'],
                  'IDENTIFY': ['to be used only in query, identify <skylivenick> <skylivepasswd>'],
                  'STATUS': ['get the status of things in skylive.', 
                             'Possible query:',
                             'telescope <num>',
                             'observatory <name|telescope num>',
                             'user <nickname>'],
                  'LASTPHOTO': ['get the latest exposure download link, both for FIT and JPEG',
                               'lastphoto <telescope num>'],
                  'LIVE': ['get the live link: live <telescope num>']
                  }
user_commands = {'QUEUE': ['not implemented yet']}
admin_commands = {'ADMIN': ['not implemented yet']}

genhelp = ["Hello, I'm the official SkyLive project IRC Bot and my commands are:",
   "FOR ALL: "+", ".join(guest_commands.keys()).lower(),
   "FOR REGISTERED SKYLIVE USERS: "+", ".join(user_commands.keys()).lower(),
   "FOR ADMINS: "+", ".join(admin_commands.keys()).lower(),
   "help <command> to get help on a specific command"]

guest_commands['HELP'] = genhelp

class botCommands:

   def __init__(self, parent):
      self.parent = parent
      self.command = self.parent.command

   def clean_line(self, line):
      wordlist = line.split(" ")
      while '' in wordlist: wordlist.remove('')
      return wordlist

   def parseCommand(self, user, channel, line):
      wordlist = self.clean_line(line)
      cmd = wordlist[0].upper()    
      if cmd in guest_commands.keys():
         f=getattr(self, 'on_'+cmd, None)
         if f and callable(f):
            return f(user, channel, line)
         else:
            return self.not_implemented(user, channel, line)


   def not_implemented(self, user, channel, msg):
      if channel == user:
         channel = user.split("!")[0]
      self.parent.msg(channel, NOT_IMPLEMENTED)


   def on_HELP(self, user, channel, msg):
      wordlist = self.clean_line(msg)
      try:
         if wordlist[1].upper() in guest_commands.keys():
            what = guest_commands[wordlist[1].upper()]
         else:
            what = genhelp
      except:
         what = genhelp
      print what
      start = user.split("!")[0]+": "
      try:
         if channel.split("!")[0] == user.split("!")[0]:
            channel = user.split("!")[0]
            start = ""
      except:
         pass
      for line in what:
         self.parent.msg(channel, start+line)



class IrcBotProtocol(irc.IRCClient):

   versionEnv = 'Debian GNU/Linux'
   versionName = 'Skylive Project Daemon (www.skylive.it)'
   versionNum = '0.1'

   def connectionMade(self):

      self.nickname = self.factory.nickname
      self.command = self.factory.command
      self.password = self.factory.password
      self.channels = self.factory.channels
      self.cmd = botCommands(self)
      log.debug("IRC Connection made")
      irc.IRCClient.connectionMade(self)

   def nickChanged(self, nick):
      self.nickname = nick

   def receivedMOTD(self, motd):
      log.debug(str("\n".join(motd)))

   def signedOn(self):
      self.msg("NickServ", "IDENTIFY "+self.password)
      channels = self.channels.split(",")
      for channel in channels:
         self.join(channel)

   def privmsg(self, user, channel, msg):
      print user, channel, msg
      if channel == self.nickname:
         return self.cmd.parseCommand(user, user, msg)
      else:
         try:
            if msg.replace(",", " ", 1).replace(":", " ", 1).split(" ",1)[0] == self.nickname:
               return self.cmd.parseCommand(user, channel, msg.replace(",", " ", 1).replace(":", " ", 1).split(" ",1)[1])
         except:
            pass
