import time

import cv2
import numpy as np

from Func.CloseProgram import Close
from Func.Helpers import CalculateWidth, CalculateHeight
from cvzone.HandTrackingModule import HandDetector

offset = 20
size = 300
folder = "Data/G"
counter = 0

cap = cv2.VideoCapture(0)
detector = HandDetector(maxHands=1)

if not cap.isOpened():
    print("Failed to open video capture.")
    exit()

while True:
    success, img = cap.read()

    if not success:
        print('can\'t read image', cap)
        break

    hands, img = detector.findHands(img)

    if hands:
        hand = hands[0]
        x, y, w, h = hand['bbox']

        imgFixed = np.ones((size, size, 3), np.uint8)
        imgCropped = img[y - offset:y + h + offset, x - offset:x + w + offset]

        aspectRatio = h / w

        if aspectRatio > 1:
            CalculateWidth(size, h, w, imgCropped, imgFixed)

        else:
            CalculateHeight(size, h, w, imgCropped, imgFixed)

        cv2.imshow('ImgCropped', imgCropped)
        cv2.imshow('ImgFixed', imgFixed)

    cv2.imshow("img", img)
    key = cv2.waitKey(1)


    if key == ord('p'):
        Close(cap)
        break

    if key == ord('s'):
        try:
            counter += 1
            cv2.imwrite(f'{folder}/Image_{time.time()}.jpg', imgFixed)
            print(f'{folder}/Image_{time.time()}.jpg')
            print(counter)
        except Exception as e:
            print(f"Error saving image: {e}")