import time
import mss
import cv2
import uuid
import numpy as np
import ctypes
import win32api
import os


keybind = '0x02' # Right Click (Default) Find other keybinds here: https://learn.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes
image_size = 640
delay_between_screenshots = 0.6 # delay in seconds
images_folder_path = 'images'
image_format = 'jpg' # change to png if you want lossless images

half_screen_x = int(ctypes.windll.user32.GetSystemMetrics(0) / 2)
half_screen_y = int(ctypes.windll.user32.GetSystemMetrics(1) / 2)
camera = mss.mss()

pause = 0
number_of_images_taken = 0
was_holding = False

box = {
    'left': int(half_screen_x - image_size//2),
    'top': int(half_screen_y - image_size//2),
    'width': int(image_size),
    'height': int(image_size)
}

if not os.path.exists(images_folder_path):
    os.mkdir(images_folder_path)
    print(f'Images folder created: /{images_folder_path}')

def is_holding_keydind():
    return win32api.GetKeyState(int(keybind, 16)) in (-127, -128)

while True:
    is_holding = is_holding_keydind()
    current_time = time.perf_counter()

    frame = np.array(camera.grab(box))

    if frame is not None:
        if is_holding and (not was_holding or (current_time - pause > delay_between_screenshots)):
            
            frame_copy = np.copy(frame)
            cv2.imwrite(f'{images_folder_path}/{str(uuid.uuid4())}.{image_format}', frame_copy)
            
            pause = current_time
            number_of_images_taken += 1
            print(f'Screenshots taken: {number_of_images_taken}')

    was_holding = is_holding
    time.sleep(0.01) # small sleep to not kill cpu performance
