LoveBOXAPIurl = 'http://yoo01pn.ddns.net:5000'
LoveBOXAPIapi = '101010'

from display import sendUpdate
import requests
from time import sleep

def listfromAPI(message):
    queueList = []
    message = message.replace("[", "").replace("]","").replace('"', "").replace("'", "")
    if message == "": print("Queue Clear"); return None
    for mess in message.split(","):
        if mess == " " or mess == "":
            continue
        if mess[0] == " ":
            queueList.append(mess[1:])
            continue
        queueList.append(mess)
    return queueList

def fixformatting(message):
    try:
        fixedmessage = [""]
        counter = 0 
        for word in message.split(" "):
            if counter + len(word) >= 22:
                counter = 0
                fixedmessage.append("\n")
                fixedmessage.append("{} ".format(word))
            else:
                counter += len(word)
                fixedmessage.append("{} ".format(word))
        return "".join(fixedmessage)
    except:
        return "".join(fixedmessage)


def main():
    response = requests.get("{}/queue?api={}".format(LoveBOXAPIurl,LoveBOXAPIapi), verify=True).content.decode()
    response = listfromAPI(response)
    if response == None: return
    if len(response) == 1:
        sendUpdate(fixformatting(response[0]))
        requests.get("{}/clear?api={}".format(LoveBOXAPIurl,LoveBOXAPIapi), verify=True).content.decode()
    

if __name__ == "__main__":
    while True:
        try:
            main()
        except:
            pass
        for i in range(1,10):
            print(i)
            sleep(1)
    
