# from PyESCPOS.impl.epson import GenericESCPOS
# from PyESCPOS.ifusb import USBConnection

# conn = USBConnection.create('5011:0416,interface=0,ep_out=3,ep_in=0')
# printer = ElginRM22(conn)
# printer.init()
# printer.text('Hello World!')


# p = Usb(0x5011, 0x0416, printer="simple")
# p.text("Hello World\n")

# p = printer.Usb(0x0416, 0x5011, 4, 0x81, 0x02) #initalize printer on raspberry pi
# p.text("hello world") #print this text
# p.cut() #move paper up enough to tear off (probably a better way, but this works.)

# import falcon
# from wsgiref import simple_server
# import os


# import os
# import falcon

# WORKING_DIRECTORY = os.getcwd()
# STATIC = 'static/'

# def apex(req, resp):
#     resp.content_type = 'text/html; charset=utf-8'
#     filename = os.path.abspath(os.path.join(WORKING_DIRECTORY, STATIC, 'index.html'))
#     with open(filename, 'rt') as f:
#         resp.body = f.read()
from escpos.printer import Usb
import usb
from wonderwords import RandomWord
from datetime import datetime
import textwrap


from .sudoku_generator import *
from .wordsearch_generator import WordSearch
from .database import TodoDatabase



class ThermalPrinter():
	def __init__(self, database):
		# self.p = printer.Usb(0x0416, 0x5011, 4, 0x81, 0x02) #initalize printer on raspberry pi
		self.database = database
		try:
			# self.p = Usb(0x0416, 0x5011, 4, 0x81, 0x02) #initalize printer on raspberry pi
			self.p = Usb(idVendor=0x0416, idProduct=0x5011, usb_args=None, timeout=4000 , in_ep=0x81, out_ep=0x02, profile="POS-5890")
			# pass
		except usb.core.NoBackendError as e:
			print(e)
			print("Try running `export DYLD_LIBRARY_PATH=/opt/homebrew/lib` if on m1 mac. source: https://github.com/pyusb/pyusb/issues/355#issuecomment-1062798576")
			raise

	def print_greeting(self):
		self.p.set(align="center")
		self.p.text(datetime.today().strftime('%Y-%m-%d'))
		self.p.set(align="left")
		self.p.text("\n\n")
		# pass #TODO: add other greetings?

	def print_todos(self, todos=[{"time": "1:00pm to 2:00pm", "text": "Read a book"}]):
		for x in self._parse_todos(todos):
			# print(x)
			this_line_width = len(x[0])+len(x[1])

			# self.p.charcode("CP437")
			self.p.set(align="left")
			self.p.text(x[0])

			output = []

			if this_line_width < 32:
				output.append( (" "*(32-this_line_width))+x[1] )
				# for s in range((32-this_line_width)):
					# self.p.text(" ")
				# self.p.text("" + " "*(32-this_line_width))
			else:
				# self.p.text(" ")
				todo_text_max_len = 32-(len(x[0])+1)
				todo_text = textwrap.wrap(x[1], todo_text_max_len)
				# t_text = textwrap.wrap()
				
				output.append(" " + todo_text[0])

				for t in todo_text[1:]:
					# self.p.text("" + " "*(len(x[0])+1) )
					# for s in range((len(x[0])+1)):
						# self.p.text(" ")

					output.append( (" "*(32-(len(x[0])+1)))+t )

					# self.p.text(t + "\n")

			print(output)
			for l in output:
				print(l)
				self.p.text(l)

			# self.p.set(align="right")
			# self.p.textln(x[1])
			# self.p.set(align="left")
			# self.p.text("\n")

	def print_sudoku(self):
		# self.p.close()
		# self.p = Usb(0x0416, 0x5011, None, 4, 0x81, 0x02)
		# self.p = Usb(idVendor=0x0416, idProduct=0x5011, usb_args=None, timeout=4000 , in_ep=0x81, out_ep=0x02, profile="POS-5890")
		convert_to_image(generate_sudoku())
		self.p.set(align="center")
		self.p.image("sudoku.png")
		# self.p.close()
		# self.p = Usb(idVendor=0x0416, idProduct=0x5011, usb_args=None, timeout=4 , in_ep=0x81, out_ep=0x02, profile="POS-5890")


	def print_random_quote(self):
		q = self.database.get_random_quote()
		self.p.text("\n\n")
		self.p.set(align="left")
		self.p.text(q[0])
		self.p.text("\n")
		self.p.set(align="right")
		self.p.text(q[1])
		self.p.text("\n")

		self.p.set(align="left")


		# pass #TODO: parse https://zenquotes.io/api/quotes (api limit is 5 req per 30 seconds)

	def print_wordsearch(self):
		# words = ("gugu,gaga")
		r = RandomWord()
		words = r.random_words(15, include_parts_of_speech=["nouns", "verbs", "adjectives"])
		w = WordSearch(','.join(words), 32, 16)

		self.p.set(align="left")
		self.p.text("Word Search:")
		self.p.text("\n\n")
		self.p.set(align="center")

		for x in w.grid:
			self.p.text(''.join(x) + "\n")

		self.p.set(align="left")
		self.p.text("\nWords: \n")
		wwords = textwrap.wrap(' '.join(words), 32)
		for word in wwords:
			# self.p.set(align="left")
			self.p.text(word + "\n")

		# Defaults.NOUNS: Represents a list of nouns
		# Defaults.VERBS: Represents a list of verbs
		# Defaults.ADJECTIVES: Represents a list of adjectives


		# def printGrid(grid):
		#     for row in grid:
		#         for column in row:
		#             print("%s" % column, end='')
		#         print()
		# printGrid(w.grid)
		# w.findWords(words.split(','))
		# print(w.wordPosition)

	def print_default(self):
		print('start 1')
		self.print_greeting()
		print('end 1')
		
		print('start 2')
		# self.print_todos()
		print('end 2')

		print('start 3')
		self.print_sudoku()
		print('end 3')
		
		print('start 4')
		self.print_wordsearch()
		print('end 4')
		
		print('start 5')
		self.print_random_quote()
		print('end 5')
		self.finished_printing()

	def _parse_todos(self, data):
		out = []
		for x in data:
			out.append(["O " + x["time"], x["text"]])
		return out
		
		#Return: ["□ 1:00pm to 2:00pm", "Read a book"]

	def finished_printing(self):
		self.p.cut() #move paper up enough to tear off (probably a better way, but this works.)


# class SyncData():
# 	def __init__(self):
# 		pass

# 	#TODO: Obtain calendar data and save to local database, parse into printable content


# class GetTodos:
# 	def on_post(self, req, resp):
# 		pass #Handle web interface requesting current todos

# class SaveTodos:
# 	def on_post(self, req, resp):
# 		pass #Handle web interface sending updated todo list

# class PrintTodos:
# 	def on_post(self, req, resp):
# 		pass #Handle web interface requesting a print action


def main():
	data = TodoDatabase()

	tp = ThermalPrinter(data)
	# tp.print_todos()
	tp.print_default()


if __name__ == '__main__':
	main()

# def main():
# 	app = falcon.App()

# 	# app.add_route('/stories', things)
# 	app.add_sink(apex, prefix='^/$')
# 	app.add_static_route('/', os.path.abspath(os.path.join(WORKING_DIRECTORY, STATIC)))

# 	# print(os.path.abspath(''))
# 	# app.add_static_route('/', os.path.abspath(''))

# 	httpd = simple_server.make_server('127.0.0.1', 8000, app)
# 	httpd.serve_forever()


# if __name__ == '__main__':
# 	main()