import os
import numpy as np

from evdev import InputDevice, ecodes
from PIL import Image

inputPath = None

for devnum in range(0,5):
	path = f"../../dev/input/event{devnum}"
	info = open(f"../../sys/class/input/event{devnum}/device/name").read().lower()
	if "ft" in info:
		inputPath = InputDevice(path)

FB = "/dev/fb0"
fb = open(FB, "wb")

Data656 = 0;


SCREEN_WIDTH = 800
SCREEN_HEIGHT = 480
if os.path.exists("../../sys/class/graphics/fb0/virtual_size"):
	vs = open("../../sys/class/graphics/fb0/virtual_size").read().strip()
	SCREEN_WIDTH, SCREEN_HEIGHT, = map(int, vs.split(","))


SCREEN_HEIGHT = 480
COLOR = (0, 0, 255)

FRAMEBUFFER = '/dev/fb0'

def RGB565_CONVERT(X, Y, rgb888Data, color, width, height):

	RGB888Image = Image.frombytes('RGB', (SCREEN_WIDTH, SCREEN_HEIGHT), rgb888Data)
	for x in range(X,width):
		for y in range(Y,height):
			RGB888Image.putpixel((x,y), color)


	RGB888 = np.array(RGB888Image)

	RR = (RGB888[:, :, 0] >> 3).astype(np.uint16) << 11
	GG = (RGB888[:, :, 1] >> 2).astype(np.uint16) << 5
	BB = (RGB888[:, :, 2] >> 3).astype(np.uint16)

	RGB565 = RR | GG | BB

	return RGB565.tobytes()



def colored_square(X, Y, WIDTH, HEIGHT, color):
	R, G, B = COLOR
	SOURCE = bytes([R,G,B] * (SCREEN_WIDTH*SCREEN_HEIGHT))

	RGB565Data = RGB565_CONVERT(X, Y, SOURCE, color, WIDTH, HEIGHT)

	with open(FRAMEBUFFER,'wb') as fb_device:
		byteWrite = fb_device.write(RGB565Data)



square_x =  200
square_y =  200
square_length = 40

R, G, B = (0,0,0)


colored_square(190, 190,250,250, (255,0,255))

input_x = None
input_y = None
clicked = 1

for event in inputPath.read_loop():
	if event.type == ecodes.EV_ABS:
		if event.code == ecodes.ABS_X:
			input_x = event.value
		if event.code == ecodes.ABS_Y:
			input_y = event.value
		if input_x is not None and input_y is not None:
			dx = input_x - square_x
			dy = input_y - square_y
			dist = (dx*dx + dy*dy) ** 0.5
			
			if dist <= square_length:
				square_x = 220
				square_y = 200

				if(clicked == 0):
					colored_square(200-10, 200-10, 200+30, 200+30, (200,0,200))
					square_x = 320
					square_y = 300

				
				if(clicked == 1):
					colored_square(300-10,300,340+50,340+50, (55,55,55))
					square_x = 320
					square_y = 300

				if(clicked == 2):
					colored_square(400-10,200-10,440+60, 240+60, (0,255,255))
					square_x = 420
					square_y = 240

				if(clicked == 3):
					colored_square(500-10,300-10,540+70,340+70, (255,0,255))
					square_x = 550
					square_y = 315
				if(clicked == 4):
					colored_square(0,0,800,480,(0,255,0))
					print("YOU DID IT!! END OF DEMO")

				clicked+=1
				
				

			input_x = None
			input_y = None
	
