import socket
import re
from colors import *
from random import randint, choice
import sys
import time
import subprocess

server = "127.0.0.1"
channel = "#bots"
if len(sys.argv) > 1: 
  channel = "#"+sys.argv[1]
botnick = "sameself"
log = channel[1:]+".log"

def ping():
    ircsock.send("PONG :Pong\n")

def joinchan(chan):
    ircsock.send("JOIN "+ chan +"\n")

def sendmsg(chan , msg): # This is the send message function, it simply sends messages to the channel.
      ircsock.send("PRIVMSG "+ chan +" :"+ msg +"\n") 

def wexec(msg):
    ircsock.send("EXEC -msg "+channel+" "+msg)

ircsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ircsock.connect((server, 6667)) # Here we connect to the server using port 6667
ircsock.send("USER "+ botnick +" "+ botnick +" "+ botnick +" :That might be a numberwang.\n") # user authentication
ircsock.send("NICK "+ botnick +"\n") # here we actually assign the nick to the bot

joinchan(channel)

def number(s):
    nm = re.match('(\d+)', s)
    if nm:
        return int(nm.groups()[0])

def rainbow(s):
  res = []
  for ch in s:
      c = choice(["blue", "green", "yellow", "magenta", "cyan", "white","red"])
      res.append(color(c)+ch)
  res.append(color("reset"))
  return "".join(res)

def send(s):
    sendmsg(channel, s)

def think(chan, nick, msg):
    words = re.split('[^\w!]+', msg)
    if len(words) > 0:
        if words[0] in {"rollcall","!rollcall", "rollcall!"}:
            send(color("red")+"Present!"+color("reset"))
        if words[0] in {"sameself"}:
            command = words[1]
            rest = words[1:]
            if command == "help":
                send(color("red")+"I just record you."+color("reset"))
            elif command == "tweet":
                send(color("yellow")+"I can't tweet :(")
            else:
                send("is "+command+" a command, "+nick+"?")

    if len(words) == 1:
        if number(words[0]):
            if randint(0,10) == 1:
                with open("wangs.txt", 'a') as f:
                    f.write(words[0]+" ")
                sendmsg(channel, words[0] + ", "+rainbow("That's Numberwang!!"))

while 1:
    ircmsg = ircsock.recv(2048)
    ircmsg = ircmsg.strip('\n\r')

    if ircmsg.find("PING :") != -1:
        ping()

    m = re.match(':(?P<nick>[a-z]+)!.*PRIVMSG #(?P<chan>\w+) :(?P<msg>.*)', ircmsg)
    if m and m.groupdict():
        m = m.groupdict()
        print "(" + m["chan"] + ")" + m["nick"] + ": " + m["msg"]
        with open(log, 'a') as f:
          f.write(time.strftime("[%H:%M:%S]", time.gmtime())+"  "+m["nick"] + ": " + m["msg"]+ "\r\n" )
        try:
            think(m["chan"], m["nick"], m["msg"])
        except:
            print "ERROR" + str(m)
