import usocket as socket
import wifi
import time
import badge
import ugfx
import dialogs

chan = "#sha2017"

def join(ch):
    global chan;
    if(len(ch)!=0):
        chan=ch;

    s.send(bytes("JOIN {}\r\n".format(chan), "UTF-8"));
    # allow posting
    ugfx.clear()
    ugfx.flush()
    ugfx.input_attach(ugfx.BTN_A, post)

def post(pressed):
    if not pressed:
        return
    dialogs.prompt_text("Message",cb=msgsend)

def msgsend(text):
    global chan;
    global messages;
    global NICK;
    messages = messages[1:] + [NICK+':'+text]
    s.send(bytes("PRIVMSG {} :{}\r\n".format(chan,text), "UTF-8"));
    ugfx.clear(ugfx.WHITE)
    for i, m in enumerate(messages):
        ugfx.string(0,i*12,m,"Roboto_Regular12",ugfx.BLACK)
    ugfx.flush()
    ugfx.input_attach(ugfx.BTN_A, post)

def exit(pushed):
    s.send(bytes("QUIT\r\n","UTF-8"))
    sys.exit()

messages = ['','','','','','','','','','Chat with the "A" Button']

ugfx.clear(ugfx.WHITE)
ugfx.string(0,0,"IRC client","Roboto_BlackItalic24",ugfx.BLACK)
ugfx.flush()

wifi.connect()
while not wifi.status():
    time.sleep(0.1)

ugfx.input_attach(ugfx.BTN_START, exit)
ugfx.string(0,36,"Connecting to WiFi","Roboto_Regular12",ugfx.BLACK)

HOST = "chat.freenode.net"
PORT = 6667

NICK = badge.nvs_get_str('owner', 'name', 'Hacker1337')+"_badge"
REALNAME = "SHA2017 attendant"

s = socket.socket()
s.connect((HOST, PORT))
s.send(bytes("NICK %s\r\n" % NICK, "UTF-8"))
s.send(bytes("USER %s 0 * :%s\r\n" % (NICK, REALNAME), "UTF-8"))
dialogs.prompt_text("Channel (default is #sha2017)",cb=join)


while 1:
    line = s.readline().rstrip()
    parts = line.split()

    if parts:
        if(parts[0] == b"PING"):
            s.send(bytes("PONG %s\r\n" % line[1], "UTF-8"))
        if(parts[1] == b"PRIVMSG"):
            msg = b' '.join(parts[3:]).decode('UTF-8')
            rnick = line.split(b'!')[0].decode('UTF-8')
            messages = messages[1:] + [rnick+msg]
            ugfx.clear(ugfx.WHITE)
            for i, m in enumerate(messages):
                ugfx.string(0,i*12,m,"Roboto_Regular12",ugfx.BLACK)
            ugfx.flush()
        print(line)
