import badge
import ugfx
import network
import time
import math
import dialogs
import usocket as socket

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 wifi_up():
  wifi_ssid = badge.nvs_get_str("badge", "wifi.ssid", "SHA2017-insecure")
  wifi_psk = badge.nvs_get_str("badge", "wifi.password", "")

  netif = network.WLAN(network.STA_IF)
  netif.active(True)
  if wifi_psk == "":
    netif.connect(wifi_ssid)
  else:
    netif.connect(wifi_ssid, wifi_psk)
  netif.isconnected()

  cur_ip = netif.ifconfig()[0]
  while True:
    if cur_ip == "0.0.0.0":
      time.sleep(1)
      cur_ip = netif.ifconfig()[0]
      pass
    else:
      break
  return cur_ip

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

  while True:
    res = s.accept()
    client_s = res[0]
    client_addr = 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)
    client_s.close()
    handler(method, url, body, headers)




print_ln("test")
print_ln("foo")
print_ln("bar")
print_ln("buzz")
