# THANKYOU
# author of the original irc_pager. beautifully simple IRC solution!
# - Pepijn de Vos (https://badge.sha2017.org/projects/irc_pager)
import badge, ugfx, appglue, wifi, time, woezel, random
import usocket as socket

color_off = bytes([0, 0, 0, 0])
color_red = bytes([7, 7, 0, 0])
color_green = bytes([7, 0, 0, 0])
color_pink = bytes([7, 50, 50, 20])
letters = '1234567890abcdefghijklmnopqrstuvwxyz'
name = badge.nvs_get_str('owner', 'name', 'n00b')
HOST = "chat.freenode.net"
PORT = 6667
NICK = name+"[love]"+random.choice(letters)+random.choice(letters)
REALNAME = name+" <3 SHA2017"
status_message = ''
irc_channel = 'sha2017'
app_name = 'love'
log_messages = []
fonts = [
  'Roboto_Regular18',
  'PermanentMarker36',
  'pixelade13'
]
is_updating = False
love_count = 0

hearts = [
  '/lib/love/heart-open.png',
  '/lib/love/heart-fill.png'
]

list_width = 90

def set_status(text):
  global status_message
  status_message = text
  redraw()
  ugfx.flush()

def clear_ghosting():
  ugfx.clear(ugfx.BLACK)
  ugfx.flush()
  badge.eink_busy_wait()
  ugfx.clear(ugfx.WHITE)
  ugfx.flush()
  badge.eink_busy_wait()

def start_self_update():
  global is_updating
  is_updating = True
  print('Starting self update')
  attempts = 0
  attempts_max = 5
  print('Waiting for network...')
  while not wifi.sta_if.isconnected():
    if attempts > attempts_max:
      print('Giving up wifi... Skipping update!')
      is_updating = False
      return
    time.sleep(.1)
    pass
  # Attempt to install new version and restart the app if it succeeds
  try:
    woezel.install(app_name)
    appglue.start_app(app_name)
  except:
    print('Update failed. May already be up to date.')
  is_updating = False

def exit_app():
  print('Exiting app...')
  appglue.home()

def blink_led(selected_color, duration=0.2):
  badge.leds_send_data(selected_color, 4)
  time.sleep(duration)
  badge.leds_send_data(color_off, 4)
  
def send_love(irc_socket):
  print('Sending love')
  irc_socket.send(bytes("NOTICE #%s :<3\r\n" % (irc_channel), "UTF-8"));
  blink_led(color_pink, .5)
  blink_led(color_pink, .5)
  blink_led(color_pink, .5)

ugfx.init()
clear_ghosting()
badge.leds_init()

def redraw():
  ugfx.clear()

  # Heart
  try:
    badge.eink_png(0, 0, hearts[0])
  except:
    print('Failed to load graphics')

  ugfx.string(0, 0, status_message, fonts[2], ugfx.BLACK)
  ugfx.string_box(20, 40, 90, 30, str(love_count), "Roboto_BlackItalic24", ugfx.BLACK, ugfx.justifyCenter)
  ugfx.string_box(115, 10, 180, 80, '[A] <3', 'PermanentMarker36', ugfx.BLACK, ugfx.justifyCenter)
  ugfx.string_box(115, 40, 180, 80, name, 'PermanentMarker22', ugfx.BLACK, ugfx.justifyCenter)
  ugfx.string(0, ugfx.height() - 13, '[FLASH app update] [B exit] [A LOVE]', fonts[2], ugfx.BLACK)

  ugfx.flush()

# Draw user interface
badge.eink_init()

print('Waiting for network...')
set_status('Waiting for network...')
wifi.init()
while not wifi.sta_if.isconnected():
  time.sleep(0.1)

set_status('Connected!')
print('Network connected!')

s = socket.socket()
#s.setblocking(False)
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"))
s.send(bytes("JOIN #%s\r\n" % (irc_channel), "UTF-8"));

ugfx.input_init()
ugfx.input_attach(ugfx.BTN_A, lambda pressed: send_love(s))
ugfx.input_attach(ugfx.BTN_B, lambda pressed: exit_app())
ugfx.input_attach(ugfx.BTN_FLASH, lambda pressed: start_self_update())

def love():
  global love_count
  love_count += 1
  redraw()

# IRC Client
while 1:
  line = s.readline().rstrip()
  parts = line.split()
  if parts:
    if (parts[0] == b"PING"):
      send_love(s)
      s.send(bytes("PONG %s\r\n" % line[1], "UTF-8"))
      blink_led(color_green)
      print('Ping/Pong')
    if (parts[1] == b"NOTICE"):
      blink_led(color_pink)
      love()
    if (parts[1] == b"PRIVMSG"):
      blink_led(color_red)
      love()