import cv2
from cvzone.HandTrackingModule import HandDetector
from time import sleep
from pynput.keyboard import Controller
import cvzone
import numpy as np


# Creating a video capture object

capture = cv2.VideoCapture(0) # Webcam id = 0 (used to access the webcam)

# Creating HD resolution for the screen
capture.set(3, 1300)  # width of screen
capture.set(4, 720)

# Hand detection code
detector = HandDetector(detectionCon=0.8 , maxHands=2)

# Keyboard Keys
keys = [["Q","W","E","R","T","Y","U","I","O","P"],
        ["A","S","D","F","G","H","J","K","L",";"],
        ["Z","X","C","V","B","N","M",",",".","/"]]

# finalText = ""

keyboard = Controller()
# draw
def drawAll(img, buttonList):
    for button in buttonList:
        x, y = button.pos
        w, h = button.size
        cv2.rectangle(img, button.pos, (x + w, y + h), (255, 0, 255), cv2.FILLED)
        cv2.putText(img, button.text, (x + 20, y + 65),
                    cv2.FONT_HERSHEY_PLAIN, 4, (255, 255, 255), 4)
    return img

# Button
class Button():
    def __init__(self , pos , text , size=[85, 85]): # size[] : size of rectangle
        self.pos = pos
        self.size = size
        self.text = text


buttonList=[]
for i in range(len(keys)):
    for j, key in enumerate(keys[i]):
        buttonList.append(Button([100 * j + 50, 100 * i + 50], key))

# Boiler plate code
while True:
    success , img = capture.read()
    img = detector.findHands(img)
    # boxing parameters and hands landmark points
    lmList , bboxInfo = detector.findPosition(img)


    img = drawAll(img, buttonList)

    if lmList:
        for button in buttonList:
            x ,y = button.pos
            w, h = button.size

            if x<lmList[8][0]<x+w and y < lmList[8][1] < y+h:
                cv2.rectangle(img, button.pos, (x + w, y + h), (175, 0, 175), cv2.FILLED)
                cv2.putText(img, button.text, (x + 20, y + 65),
                            cv2.FONT_HERSHEY_PLAIN, 4, (255, 255, 255), 4)
                l, _, _ = detector.findDistance(8, 12, img,draw=False)
                print(l)

                # When the clicks happens
                if l < 30:
                    keyboard.press(button.text)
                    cv2.rectangle(img, button.pos, (x + w, y + h), (0, 255, 0), cv2.FILLED)
                    cv2.putText(img, button.text, (x + 20, y + 65),
                                cv2.FONT_HERSHEY_PLAIN, 4, (255, 255, 255), 4)
                    # finalText += button.text
                    sleep(0.20)

   # cv2.rectangle(img, (50, 350), (700, 450), (175, 0, 175), cv2.FILLED)
    # cv2.putText(img, finalText, (60,430),
     #           cv2.FONT_HERSHEY_PLAIN, 5, (255, 255, 255), 5)


    cv2.imshow("Image", img)
    cv2.waitKey(1) # giving 1ms delay