import os
import time
import traceback
import json
import re
import os
import requests
import re

import serial
uart = serial.Serial("/dev/serial0", 19200, timeout=3000)


import adafruit_thermal_printer
ThermalPrinter = adafruit_thermal_printer.get_printer_class(2.69)
printer= ThermalPrinter(uart)



def check_file():
    datanames = []
    filenamelength = 7

    # Define the remote file to retrieve
    remote_url = 'https://onesheepforalifetime.com/static/json/'
    # Define the local filename to save data
    local_file = 'local_copy.json'
    # Make http request for remote file data
    data = requests.get(remote_url)
    text = data.text
    print(text)
    text = text.split("<table>")[1]
    #print(text)
    amount = re.findall('json',text)
    amount = len(amount)
    check = int(amount)

    while True:
        time.sleep(1)
        print("waiting for a filechange on server")
        # Define the remote file to retrieve
        
        # Define the local filename to save data
        local_file = 'local_copy.json'
        # Make http request for remote file data
        data = requests.get(remote_url)
        text = data.text
        text = text.split("<table>")[1]
        #print(text)
        amount = re.findall('json',text)
        amount = len(amount)
        amount = int(amount)

        if amount != check:
            for i in range(amount):
                print(text)
                index = text.find("json")
                datanames.append(text[index-filenamelength:index+4])
                text = text[index+4:-1]

            del datanames[::2]  # delete every second element (counting from the first)

            for filename in datanames:
                print(filename)
            
                with open(local_file, 'wb')as file:
                    data = requests.get(remote_url + filename)
                    print("new file has been uploaded:")
                    print(data.content)
                    content = data.content
                    content = content[1:]
                    content = content[:-1]
                    content = content.decode('utf-8')
                    content = content.split(",")
                    garment_count = content[0]
                    name = content[2]
                    total_wool_g = content[3]
                    total_wool_m = content[4]
                    
                    garment_name = []
                    garment_wool_g = []
                    garment_stichtype = []
                    garment_tension = []
                    x = 0
                    
                    for i in range(int(garment_count)):
                        garment_name.append(content[5+x])
                        garment_wool_g.append(content[6+x])
                        garment_stichtype.append(content[7+x])
                        garment_tension.append(content[8+x])
                        x = x + 4
                    
                    try:
                        tprint(garment_count,name,total_wool_g,total_wool_m, garment_name,garment_wool_g,garment_stichtype,garment_tension)
                        
                    except:
                        pass
                    
                    finally:
                        print("something failed")
                        
                    check_file()

            check = check + 2




    #return(link)

def tprint(garmencount, name, total_wool_g,total_wool_m,g_title,g_usedy,g_stichtype,g_tension):
    
    printer.justify = adafruit_thermal_printer.JUSTIFY_CENTER



        qoute =[
    '"To counteract consumerism, the only way is to keep. [...] Even if it costs me more to repair something than buying it new, I choose to keep."',
    '"Clothes have always been at the centre of our lives, marking our rituals, representing identity, profession, rank and status, but they have profound social implications as well. What we wear often brings us together with others who wear similar things, helping us to find our people, connect and belong."',
    '"Maintenance is a word we no longer associate with clothing at all, but it lies at the crux of the problem, and is a way to define part of the solution, a way to redress the balance between consumption and disposal."',
    '"We become with each other, or not at all."',
    '"Properly practiced, knitting soothes the troubled spirit, and it does not hurt the untroubled spirit either."',
    'You do not knit because you are patient. You are patient because you knit."'
    ]

    author = [
        "Orsola de Castro in her book 'Loved Clothes Last'",
        "Orsola de Castro in her book 'Loved Clothes Last'",
        "Orsola de Castro in her book 'Loved Clothes Last'",
        "Donna Haraway, (from her book Staying with the Trouble, an elaboration on why we need to form bonds with the other species on earth in order to survive and thrive)",
        "Elizabeth Zimmerman in 'Knitting Without Tears'",
        "Stephanie Pearl-McPhee in 'Things I Learned From Knitting'",
    ]


    x = random.randint(0,5)
    qoute = qoute[x]
    author = author[x]





    printer.feed(5)
    if name != "":
        printer.print(name + " Wool Report")

    else:
        printer.print("Your Wool Report")
        
    printer.feed(2)
    printer.print("***************************")
    printer.print("***************************")
    printer.feed(2)
    printer.print("Wool used:" + total_wool_g + " grams")
    printer.print("Wool dontaed:" + total_wool_m + " grams")
    printer.feed(2)
    printer.print("***************************")
    printer.print("***************************")
    printer.feed(2)
    for i in range(len(g_title)):
            printer.print(g_title[i])
            printer.print(g_usedy[i] + " grams")
            printer.print(g_stichtype[i])
            printer.print(g_tension[i])
            printer.feed(2)
    printer.print("***************************")
    printer.print("***************************")
    printer.feed(2)
    printer.print(qoute)
    printer.feed(1)
    printer.print(author)
    printer.feed(2)
    printer.print("onesheepforalifetime.com")
    printer.feed(15)


check_file()
    
    