import badge, ugfx, uos, appglue, re #, gc 

badge.init()
ugfx.init()
ugfx.input_init()

ugfx.clear(ugfx.BLACK)
ugfx.flush()
ugfx.clear(ugfx.WHITE)

path='/lib'
lights=0
brightness=5
bookmode=0

def show_cover(bi):
  global path
  global books
  
  fpath=path+'/book_'+books[bi]+'.txt'
  print("Show %s -> %s!" % (books[bi], fpath))
  cffile=open(fpath,'r')
  try: 
    for cfline in cffile:
      #print(cfline) this line makes it crash hard
      t=cfline.split('=')
      if(t[0]=='title'):
        title=t[1]
      if(t[0]=='author'):
        author=t[1]
      if(t[0]=='summary'):
        summary=t[1]

  except Exception as e: 
    print("Couldn't open %s?\nError:%s " % (fpath,str(e)))
  finally:
    cffile.close()

    ugfx.clear(ugfx.WHITE)
    ugfx.string(150, 20, title , "Roboto_BlackItalic12", ugfx.BLACK)
    ugfx.string(150, 40, author , "Roboto_BlackItalic12", ugfx.BLACK)
    ugfx.string(150, 60, summary , "Roboto_BlackItalic12", ugfx.BLACK)
    badge.eink_png(0,0,path+'/'+books[bi]+".png")

def test_file():
  global files
  global options
  global path
  global bookmode
  
  index = options.selected_index()
  if bookmode>0:
    #searchObj = re.search( r'^book_(\w+)', files[index-1] )
    show_cover(index)
  else:
    if index>0 and options.selected_index()<=len(files):

      ugfx.area(150,20,150,40,ugfx.WHITE)

      if index>0:	
        fpath=path+'/'+files[index-1]
        ugfx.string(150, 20, "f%d:%s" % (index,fpath), "Roboto_BlackItalic12", ugfx.BLACK)
        print("Statting %s" % fpath)

        filestat=uos.stat(fpath)
        if filestat[0]==16895:
          ugfx.string(150, 40, "Directory" , "Roboto_BlackItalic12", ugfx.BLACK)
        if filestat[0]==33279:   
          ugfx.string(150, 40, "File %d bytes" % filestat[6], "Roboto_BlackItalic12", ugfx.BLACK)

    else:
      ugfx.string(150, 20, "Directory back ", "Roboto_BlackItalic12", ugfx.BLACK)
  ugfx.flush()
  #gc.collect()
  
def update_filelist():
  global path
  global options
  global files
  global bookmode
  global books
  bookmode=0
  books=[]
  print("i want to read %s" % path)
  while options.count() > 0:
    options.remove_item(0)
  #uos.chdir(path)
  #if path=='/':
  #  files=uos.listdir('/')
  files=uos.listdir(path)
  options.add_item("<- Go Dir Up")
  for file in files:
    options.add_item("%s" % file)
    searchObj= re.search( r'^book_(\w+)',file)
    if (searchObj):
      bookmode=1
      break
  if(bookmode):
    while options.count() > 0:
    	options.remove_item(0)
    for file in files:
    	searchObj= re.search( r'^book_(\w+)',file)
    	if (searchObj):
          options.add_item("%s" % searchObj.group(1))
          books+=[searchObj.group(1)]
	ugfx.input_attach(ugfx.BTN_B, lambda pushed: update_filelist() if pushed else False)
	ugfx.input_attach(ugfx.BTN_A, lambda pushed: open_book() if pushed else False)
  else: 
    ugfx.input_attach(ugfx.BTN_B, lambda pushed: dir_up() if pushed else False)
    ugfx.input_attach(ugfx.BTN_A, lambda pushed: open_book() if pushed else False)
  ugfx.area(150,20,150,40,ugfx.WHITE)
  ugfx.string(150, 20, "Current path: %s" % path, "Roboto_BlackItalic12", ugfx.BLACK) 
  #gc.collect()

def text_settings():
  global brightness
  
  if (brightness==0):
    print("Lights off")
    badge.leds_disable()
    brightness=5
  else:
    print("Lights on")
   
    badge.leds_enable()
    #badge.leds_send_data(bytes([brightness,brightness,brightness,brightness,brightness,brightness,brightness,brightness,brightness,brightness,brightness,brightness,brightness,brightness,brightness,brightness,brightness,brightness,brightness,brightness,brightness,brightness,brightness,brightness]), 24)
    badge.leds_send_data(bytes([0,0,0,brightness,0,0,0,brightness,0,0,0,brightness,0,0,0,brightness,0,0,0,brightness,0,0,0,brightness]), 24)
  brightness=brightness*2
  if brightness>105:
    brightness=0
    
def open_book():
  global books
  
  index = options.selected_index()
  fpath=path+'/'+books[index]+'.ch1.txt'
  open_file(fpath)
    
def open_file(fpath):
  global line
  line=0
  text_render(fpath,0)
  ugfx.input_attach(ugfx.BTN_B, lambda pushed: filepick() if pushed else False)
  ugfx.input_attach(ugfx.JOY_UP, lambda pushed: text_render(fpath,-1) if pushed else False)
  ugfx.input_attach(ugfx.JOY_DOWN, lambda pushed: text_render(fpath,1) if pushed else False)
  ugfx.input_attach(ugfx.JOY_LEFT, lambda pushed: text_render(fpath,-9) if pushed else False)
  ugfx.input_attach(ugfx.JOY_RIGHT, lambda pushed: text_render(fpath,9) if pushed else False)
  ugfx.input_attach(ugfx.BTN_SELECT, lambda pushed: text_settings() if pushed else False)
  
def text_render(fpath,scroll):
  global line
  line+=scroll
  t=0

  if line<0:
    line=0
  print("%s(%d) " % (fpath,line) )  
  textfile=open(fpath,"r")
  ugfx.clear(ugfx.WHITE)

  for textline in textfile:
    if t>=line and t<(line+9):
      ugfx.string(0, (t-line)*13, textline, "Roboto_BlackItalic12", ugfx.BLACK)
    t=t+1
    if t>(line+9):
      break
  if t>=line and t<(line+8):
    line=line-9
      
  textfile.close()  
  ugfx.flush()
  
  
def open_png(fpath):
  ugfx.clear(ugfx.WHITE)
  badge.eink_png(0,0,fpath)
  ugfx.flush()
  ugfx.input_attach(ugfx.BTN_B, lambda pushed: filepick() if pushed else False)
  ugfx.input_attach(ugfx.JOY_UP, 0)
  ugfx.input_attach(ugfx.JOY_DOWN, 0)
  ugfx.input_attach(ugfx.JOY_LEFT, 0)
  ugfx.input_attach(ugfx.JOY_RIGHT, 0)
  ugfx.input_attach(ugfx.BTN_SELECT, 0)
  
def select_file():
  global files
  global options
  global path
  
  index = options.selected_index()
  print("Select file %d: %s" % (index-1,files[index-1]))
  ugfx.area(150,20,150,40,ugfx.WHITE)
  if index> 0:
    ugfx.string(150, 40, "Open %s?" % files[index-1], "Roboto_BlackItalic12", ugfx.BLACK)
    fpath=path+'/'+files[index-1]
    filestat=uos.stat(fpath)
    if filestat[0]==16895: # check if it is a directory
      path=fpath
      update_filelist()
      #ugfx.string(150, 40, "Directory" , "Roboto_BlackItalic12", ugfx.BLACK)
    if filestat[0]==33279:   # its a file
      #ugfx.string(150, 40, "File %d bytes" % filestat[6], "Roboto_BlackItalic12", ugfx.BLACK)
    
      searchObj = re.search( r'.png$', files[index-1] )
      if searchObj:
        print("Open png")
        open_png(fpath)
      else:
        open_file(fpath)
  else:
    ugfx.string(150, 40, "Going up", "Roboto_BlackItalic12", ugfx.BLACK)
    #directory back
    #split_path = path.strip('/').split('/')
    #path = '/' + '/'.join(split_path[:-1])
    #temppathlist=path.split('/')
    #del temppathlist[len(temppathlist)-1];
    #path=''
    #for part in temppathlist:
    #  searchObj = re.search( r'^/', part )
    #  print("Part:%s" % part)
    #  if searchObj:
    #    print("Match!")
    #  	path=path+part
    #  else:
    #    if len(part)>0:
    #    	path=path+'/'+part
    #if path=='':
    #  path='/'
    dir_up()
  ugfx.flush()
  
def dir_up():
  global path
  split_path = path.strip('/').split('/')
  path = '/' + '/'.join(split_path[:-1])
  update_filelist()

def filepick():
  global options
  global files
  global path
  
  ugfx.clear(ugfx.WHITE)
  ugfx.set_lut(ugfx.LUT_FASTER)
  ugfx.flush()
  options = ugfx.List(0,0,int(ugfx.width()/2),ugfx.height())

  ugfx.string(150, 0, "Use A to select file %d" % (options.selected_index()), "Roboto_BlackItalic12", ugfx.BLACK)
  update_filelist()
  #options.selected_index(0)

  ugfx.input_attach(ugfx.JOY_UP, lambda pushed: test_file() if pushed else False)
  ugfx.input_attach(ugfx.JOY_DOWN, lambda pushed: test_file() if pushed else False)
  ugfx.input_attach(ugfx.JOY_LEFT, 0)
  ugfx.input_attach(ugfx.JOY_RIGHT, 0)
  ugfx.input_attach(ugfx.BTN_SELECT, lambda pushed: text_settings() if pushed else False)
  ugfx.input_attach(ugfx.BTN_A, lambda pushed: select_file() if pushed else False)
  ugfx.input_attach(ugfx.BTN_B, lambda pushed: appglue.start_app("launcher", False) if pushed else False)

  ugfx.flush()
  ugfx.set_lut(ugfx.LUT_NORMAL)

try:
  badge.leds_init()
  filepick()
  print("All systems go!")

except Exception as e: 
  #probably a bug:
  ugfx.string(50, 50,str(e), "Roboto_BlackItalic12", ugfx.BLACK)
  ugfx.flush()
  #dont re-raise it in the hope the user can continue
  #raise e