import badge
import ugfx
import wifi
import os

badge.init()
ugfx.init()
wifi.init()

ugfx.clear(ugfx.BLACK)
ugfx.flush()
ugfx.clear(ugfx.WHITE)
ugfx.flush()
ugfx.clear(ugfx.BLACK)
ugfx.flush()
ugfx.clear(ugfx.WHITE)
ugfx.flush()

path = 'lib/espixelflut'
os.chdir(path)
files = os.listdir()

import re
i = 0
toRemoveList = []
for file in files:
  m = re.match(r"ACKtree_([a-zA-Z0-9]+)\.py", file)
  if not m:
    toRemoveList.append(file)
  else:
    files[i] = m.group(1)
  i += 1
for toRemove in toRemoveList:
  files.remove(toRemove)

pos = 0
def selectionScreen(change = 0, pressed = False):
  global pos
  global files

  if pressed and (change != -1 or pos > 0) and (change != 1 or pos < len(files) - 1):
    pos += change

    i = 0
    for file in files:
      if i == pos:
        color = ugfx.BLACK
      else:
        color = ugfx.WHITE
      ugfx.thickline(0, 6+i*12, 148, 6+i*12, color, 12, 0)
      i += 1
    i = 0
    for file in files:
      if i == pos:
        color = ugfx.WHITE
      else:
        color = ugfx.BLACK
      ugfx.string(0,i*12,file,"Roboto_Regular12",color)
      i += 1
    ugfx.flush()

def startScript(pressed = False):
  global files
  global pos

  if pressed:
    execfile('ACKtree_'+files[pos]+'.py')

def setConfig(pressed = False):
  if pressed:
    pass

selectionScreen(0, True)

ugfx.input_init()
ugfx.input_attach(ugfx.JOY_UP, lambda pressed: selectionScreen(-1, pressed))
ugfx.input_attach(ugfx.JOY_DOWN, lambda pressed: selectionScreen(1, pressed))
ugfx.input_attach(ugfx.BTN_A, lambda pressed: startScript(pressed))
#ugfx.input_attach(ugfx.BTN_SELECT, lambda pressed: setConfig(pressed))

while True:
  pass