import ugfx, badge, wifi, time, usocket as socket, system, keyboard

def show (str1="",str2="",str3="",str4="",str5="",str6=""):
  ugfx.clear(ugfx.BLACK)
  ugfx.string(15, 5, str1, "Roboto_Regular12", ugfx.WHITE)
  ugfx.string(15, 20, str2, "Roboto_Regular12", ugfx.WHITE)
  ugfx.string(15, 35, str3, "Roboto_Regular12", ugfx.WHITE)
  ugfx.string(15, 50, str4, "Roboto_Regular12", ugfx.WHITE)
  ugfx.string(15, 65, str5, "Roboto_Regular12", ugfx.WHITE)
  ugfx.string(15, 70, str6, "Roboto_Regular12", ugfx.WHITE)
  #easydraw.battery(1, 1, 1)
  ugfx.flush()

def clear ():
  ugfx.clear(ugfx.WHITE)
  ugfx.flush()
  badge.eink_busy_wait()
  ugfx.clear(ugfx.BLACK)
  ugfx.flush()
  badge.eink_busy_wait()

def connect():
  try:
    show("Connecting to socket on " + HOST,"on port " + PORT)
    s = socket.socket()
    s.connect(socket.getaddrinfo(HOST, PORT)[0][-1])
    try:
      reply = s.recv(4096).decode('utf-8')
      show("MPD version",reply.replace("OK ",""),"")
      return s
    except:
      return None
  except:
    askHost()
    askPass()
    return None

def mpdCommand ( command ):
  try:
    s.send(command + " \n")
  except:
    system.start("mpdclient")
  reply = s.recv(4096).decode('utf-8')
  return reply

def showMain ():
  #currentsong part
  reply = mpdCommand("currentsong")
  replylines = reply.split('\n')[:-2]
  mySongDict = dict( (line.split(": ", 1)) for line in replylines)
  if not 'Artist' in mySongDict:
    myArtist = ""
  else:
    myArtist = mySongDict['Artist']
  if not 'Title' in mySongDict:
    myTitle = ""
  else:
    myTitle = mySongDict['Title']
  if not 'file' in mySongDict:
    myFile = ""
  else:
    myFile = mySongDict['file']
  #status part
  global myRandom
  global myRepeat
  global myState
  reply = mpdCommand("status")
  replylines = reply.split('\n')[:-2]
  myStatusDict = dict( (line.split(": ", 1)) for line in replylines)
  if not 'volume' in myStatusDict:
    myVolume = ""
  else: myVolume = myStatusDict['volume']
  if not 'random' in myStatusDict:
    myRandom = "unknown"
  else:
    if myStatusDict['random'] == '1':
      myRandom = "On"
    else:
      myRandom = "Off"
  if not 'repeat' in myStatusDict:
    myRepeat = "unknown"
  else:
    if myStatusDict['repeat'] == '1':
      myRepeat = "On"
    else:
      myRepeat = "Off"
  if not 'state' in myStatusDict:
    myState = "unknown"
  else: myState = myStatusDict['state']
  #draw result
  show( "Vol: " + myVolume + " Repeat: " + myRepeat + " Random: " + myRandom + " State: " + myState,
 myArtist , myTitle , myFile , "" , "Batt: " + str(badge.battery_volt_sense()/1000) + "V" )

def vol_up (pushed):
  if pushed:
    mpdCommand("volume 5")
    showMain()
    print("vol_up")
def vol_down(pushed):
  if pushed:
    mpdCommand("volume -5")
    showMain()
    print("vol_down")
def prev(pushed):
  if pushed:
    mpdCommand("previous")
    showMain()
    print("previous song")
def nxt(pushed):
  if pushed:
    mpdCommand("next")
    showMain()
    print("next song")
#Start button
def toggle_play(pushed):
  if pushed:
    if myState == 'pause' or myState == 'stop':
      mpdCommand("play")
      print("playing")
    elif myState == 'play':
      mpdCommand("pause")
      print("paused")
    showMain()
#Select button
def return_home(pushed):
  if pushed:
    print("returning home")
    system.home()
#A button
def toggle_random(pushed):
  if pushed:
    if myRandom == "Off":
      mpdCommand("random 1")
      print("turned random on")
    else:
      mpdCommand("random 0")
      print("turned random off")
    showMain()
#B button
def toggle_repeat(pushed):
  if pushed:
    if myRepeat == "Off":
      mpdCommand("repeat 1")
      print("turned repeat on")
    else:
      mpdCommand("repeat 0")
      print("turned repeat off")
    showMain()

dialogResult = None
def dialogCb(result):
  global dialogResult
  dialogResult = result
	
def askHost():
  global dialogResult
  dialogResult = None
  keyboard.show("Set hostname","",dialogCb)
  while dialogResult == None:
	time.sleep(0.1)
  badge.nvs_set_str("mpdclient", "host", dialogResult)
  return myHost

def askPort():
  global dialogResult
  dialogResult = None
  keyboard.show("Set port","",dialogCb)
  while dialogResult == None:
	time.sleep(0.1)
  badge.nvs_set_str("mpdclient", "port", dialogResult)
  return myPort

def askPass():
  global dialogResult
  dialogResult = None
  keyboard.show("Set password","",dialogCb)
  while dialogResult == None:
	time.sleep(0.1)
  badge.nvs_set_str("mpdclient", "password", dialogResult)

def setupButtons():
  ugfx.input_attach(ugfx.JOY_UP, vol_up)
  ugfx.input_attach(ugfx.JOY_DOWN, vol_down)
  ugfx.input_attach(ugfx.JOY_LEFT, prev)
  ugfx.input_attach(ugfx.JOY_RIGHT, nxt)
  ugfx.input_attach(ugfx.BTN_START, toggle_play)
  ugfx.input_attach(ugfx.BTN_SELECT, return_home)
  ugfx.input_attach(ugfx.BTN_A, toggle_random)
  ugfx.input_attach(ugfx.BTN_B, toggle_repeat)

badge.init()
ugfx.init()
ugfx.input_init()
wifi.connect()

HOST = badge.nvs_get_str("mpdclient", "host", "")
PORT = badge.nvs_get_str("mpdclient", "port", "6600")
PASSWORD = badge.nvs_get_str("mpdclient", "password", "")

if len(HOST) < 1:
  HOST = askHost()
show("Connecting","teh","wifis")
if not wifi.wait():
  show("could not connect to wifi","teh","wifis")
  time.sleep(1)
  system.launcher()

s = connect()
reply = mpdCommand("currentsong")
if "permission" in reply:
  try:
    if PASSWORD:
      reply = mpdCommand("password " + PASSWORD )
      if reply.strip() == "OK":
        show("Password accepted")
      else:
        show("Password not accepted")
        time.sleep(2)
        askPass()
        system.start("mpdclient")
    else:
      askPass()
      system.start("mpdclient")
  except:
    pass
setupButtons()
clear()
while 1:
  showMain()
  time.sleep(10)

s.close()