import os
import time
import traceback
import json
import re
from fpdf import FPDF, HTMLMixin
import os

from pdf2image import convert_from_path, convert_from_bytes
from PIL import Image, ImageFont, ImageDraw 

import requests
import re



class FileModified():
	def __init__(self, file_path, callback):
		self.file_path = file_path
		self.callback = callback
		self.modifiedOn = os.path.getmtime(file_path)


	def start(self):
			try:
				while (True):
					time.sleep(0.5)
					modified = os.path.getmtime(self.file_path)
					if modified != self.modifiedOn:
						self.modifiedOn = modified
						if self.callback():
							break
			except Exception as e:
				print(traceback.format_exc())

def file_modified():
	print("running thermal printer")
	f = open('media/sample.json')
	data = json.load(f)
	stichtype = data['stichtype']
	size = data['size']
	create_pdf("Max",stichtype)
	f.close()
	return False


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:
			
				with open(local_file, 'wb')as file:
					data = requests.get(remote_url + filename)
					print("new file has been uploaded:")
					print(data.content)

			check = check + 2

class PDF(FPDF, HTMLMixin):
	pass

def create_pdf():

	name = "Max" + "'s"
	total_wool_m = 128
	total_wool_g = 980
	leftover_wool_m = 2
	leftover_wool_g = 20
	purpose = ">> donated to the community"
	images = ["Wool-01.png","Wool-01.png","Wool-01.png"]
	g_title = ["Pullover","Socks","Scarf"]
	g_usedy = ["152m","75m","25m"]
	g_usedm = ["720g","300g","100g"]
	g_stichtype = ["stocking","stocking","stocking"]
	g_tension = ["no 1.","no 1.","no 1."]
	debug = 0

	h = 14
	sh = 10
	p = 8


	width = 57
	image_width = width - 8
	height = 189 + len(g_title) * 69 + 41

	pdf =  PDF('P', 'mm', (width, height))
	# Add a page
	pdf.add_page()
	pdf.set_margins(4.5,0,4.5)
	pdf.set_font("Arial", size = h)
	
	 
	# create a cell
	#pdf.write(10, name +  "Wool Report")
	pdf.set_font("Arial", size = h, style="B")
	pdf.cell(0,1, txt= "", border=debug, align="C", ln=1)
	pdf.cell(0,5, txt= name +  "Wool Report", border=debug, align="C", ln=1)
	
	
	pdf.cell(0,5, txt= " ",border= debug,align="C",ln=1)
	pdf.image("Wool-01.png", x = (width-image_width)/2, y = 21, w = image_width) #-------------------------------------
	pdf.cell(0,image_width, border=debug, align="C",ln=1)
	pdf.set_font("Arial", style="BU", size = sh)
	pdf.cell(0,5, txt= "Wool used",  border=debug, align="C",ln=1)
	pdf.set_font("Arial", size = p)
	pdf.cell(0,5, txt= str(total_wool_g) + " g" , border=debug, align="C",ln=1)
	pdf.cell(0,5, txt= str(total_wool_m) + " m" , border=debug, align="C",ln=1)


	pdf.cell(0,5, txt= " ",border= debug,align="C",ln=1)
	pdf.image("Wool-01.png", x = (width-image_width)/2, y = 90, w = image_width) #-------------------------------------
	pdf.cell(0,image_width, border=debug, align="C",ln=1)
	pdf.set_font("Arial", size = sh, style="BU" ) 
	pdf.cell(0,5, txt= "Wool Leftovers",border=debug, align="C",ln=1)
	pdf.set_font("Arial", size = p)
	pdf.cell(0,5, txt= str(leftover_wool_g) + " g" , border=debug, align="C",ln=1)
	pdf.cell(0,5, txt= str(leftover_wool_m) + " m" , border=debug, align="C",ln=1)
	pdf.cell(0,5, txt= "" , border=debug, align="C",ln=1)
	pdf.cell(0,5, txt= purpose , border=debug, align="C",ln=1)



	pdf.cell(0,10, txt= " " , border=debug, align="C",ln=1)


	pdf.cell(0,5, txt= " ",border= debug,align="C",ln=1)
	pdf.set_font("Arial", size = h, style="B")
	pdf.cell(0,5, txt= "Your Wardrobe", border=debug, align="C", ln=1)
	
	blockheight = 0
	for i in range(len(images)):
		pdf.cell(0,5, txt= " ",border= debug,align="C",ln=1)
		pdf.image(images[i], x = (width-image_width)/2, y = 189 + blockheight, w = image_width) #-------------------------------------
		pdf.cell(0,image_width, border=debug, align="C",ln=1)
		pdf.set_font("Arial", size = sh, style="BU")
		pdf.cell(0,10, txt= g_title[i], border=debug, align="C",ln=1)
		pdf.set_font("Arial", size = p)
		pdf.cell(0,5, txt= g_usedy[i] + ", " + g_usedm[i] + ", " + g_stichtype[i] + ", " + g_tension[i], border=debug, align="C",ln=1)

		blockheight = blockheight + image_width + 20
		

	pdf.set_font("Arial", size = p, style="")
	pdf.cell(0,10, txt= "",border= debug,align="C",ln=1)
	pdf.cell(0,5, txt= "----------------------------------------",border= debug,align="C",ln=1)
	pdf.cell(0,10, txt= "domainnamegoeshere.at",border= debug,align="C",ln=1)
	pdf.set_font("Arial", size = p)

	fpath = "Hello.pdf"
	pdf.output(fpath)



	images = convert_from_bytes(open(fpath, 'rb').read(),poppler_path=r"C:\Program Files (x86)\poppler-0.68.0\bin")
	for i in range(len(images)):
		images[i].save('page'+ str(i) +'.jpg', 'JPEG')




	#return(link)



check_file()
#create_pdf()
#fileModifiedHandler = FileModified(r"sample.json",file_modified)
#fileModifiedHandler.start()

