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()


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_connect(host, port):
  s = socket.socket()
  ai = socket.getaddrinfo(host, port)
  addr = ai[0][-1]
  s.connect(addr)
  return (s, addr[0])


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






def connect_mode():
  host = str(dialogs.prompt_text("Enter host:"))
  port = int(dialogs.prompt_text("Enter port:"))
  s,addr = socket_connect(host, port)
  print_ln("Connected to %s(%s) on port %d..." % (host, addr[0], port))
  ugfx.input_attach(ugfx.BTN_START, lambda pressed: thread.start_new_thread(send_message, (pressed,)))
  while True:
    cline = s.readline()
    print_ln(cline)


def listen_mode():
  port = int(dialogs.prompt_text("Enter port"))
  while True:
    pass




connect_mode()
