import badge
import ugfx
import network
import wifi
import time
import math
import dialogs
import usocket as socket
import _thread as thread


badge.init()
ugfx.init()
wifi.init()

ugfx.clear(ugfx.WHITE)
ugfx.flush()
ugfx.clear(ugfx.BLACK)
ugfx.flush()
ugfx.clear(ugfx.WHITE)
ugfx.flush()

lines = []
def render_term():
  ugfx.clear(ugfx.WHITE)
  ugfx.flush()
  cy = 0
  h = ugfx.height()
  count = math.floor(h / 13)
  for line in lines[-count:]:
    ugfx.string(0, cy, line, "pixelade13", ugfx.BLACK)
    cy = cy + 13
    if cy > h:
      break
  ugfx.flush()


def print_ln(text):
  lines.append(text)
  render_term()



def send_message(pressed):
  msgb = bytes(dialogs.prompt_text("Your message:") + "\n")
  s.send(msgb)


def wifi_up():
  while not wifi.sta_if.isconnected():
    time.sleep(0.1)
    pass
  return wifi.sta_if.ifconfig()[0]


def socket_listen(port):
  s = socket.socket()
  ai = socket.getaddrinfo("0.0.0.0", port)
  addr = ai[0][-1]
  # s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  s.bind(addr)
  s.listen(5)
  return s


def webserver(s, handler):
  run = True
  while run:
    res = s.accept()
    client_s = res[0]
    client_ip = res[1]
    req = str(client_s.readline().decode("ascii")).split(" ")
    method = req[0]
    url = req[1]
    headers = []
    while True:
      cline = str(client_s.readline().decode("ascii"))
      if cline == "" or cline == "\r\n":
        break
      headers.append(cline)
    body = ""
    if method.upper == "POST":
      body = client_s.recv(8192)
    resp = bytes(handler(client_s, method, url, body, headers, client_ip).encode("utf-8"))
    client_s.send(resp)
    client_s.close()


def hello_handler(s, method, url, body, headers, client_ip):
  if url == "/":
    print_nl("Serving / to " + str(client_ip))
    return """\
HTTP/1.0 200 OK
Server: SHA2017 Badge
Content-Type: text/html

<h1>Hello World!</h1>
"""
  else:
    print_nl("Not found: " + str(url) + " from client " + str(client_ip))
    return """\
HTTP/1.0 404 Not Found

<h1>The reqested URL cold not be found on this badge </h1>
"""


print_ln("Waiting for wifi...")
cur_ip = wifi_up()
print_ln("Your IP: " + cur_ip)

print_ln("Creating listening socket on port 8080...")
s = socket_listen(8080)
print_ln("Starting webserver...")
webserver(s, hello_handler)
