import cv2  # opencv
import uuid
import os
import time
from pathlib import Path


# Define the labels
labels = ['thumbsup', 'thumbsdown', 'thankyou', 'livelong']
number_imgs = 5


# Create some folders for the images
IMAGES_PATH = Path(os.path.join('Tensorflow', 'workspace',
                                'images', 'collectedimages'))
if not IMAGES_PATH.exists():
    IMAGES_PATH.mkdir(parents=True, exist_ok=True)


for label in labels:
    (IMAGES_PATH / label).mkdir(parents=True, exist_ok=True)


# Capture some images
for label in labels:
    # Connect to the webcam or capture device; may need to update the deviceID
    cap = cv2.VideoCapture(0)
    print(f'Collecting images for {label}')
    time.sleep(5)
    for imgnum in range(number_imgs):
        print(f'Collecting image# {imgnum}')
        ret, frame = cap.read()
        imgname = str(IMAGES_PATH / label / f'{label}.{str(uuid.uuid1())}.jpg')
        cv2.imwrite(imgname, frame)
        cv2.imshow('frame', frame)
        time.sleep(2)

        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
# remember to release the capture device again
cap.release()
cv2.destroyAllWindows()


# Image labelling
LABELIMG_PATH = Path(os.path.join('Tensorflow', 'labelimg'))
if not LABELIMG_PATH.exists():
    LABELIMG_PATH.mkdir(parents=True, exist_ok=True)
    os.system(
        f"git clone https://github.com/heartexlabs/labelImg {LABELIMG_PATH}")
    if os.name == 'posix':
        os.system(f"cd {LABELIMG_PATH} && make qt5py3")
    if os.name == 'nt':
        os.system(
            f"cd {LABELIMG_PATH} && pyrcc5 -o libs/resources.py resources.qrc")
os.system(f"cd {LABELIMG_PATH} && python labelImg.py")


# Split into Training and Testing partitions
TRAIN_PATH = Path(os.path.join('Tensorflow', 'workspace',
                               'images', 'train'))
TEST_PATH = Path(os.path.join('Tensorflow', 'workspace',
                              'images', 'test'))
TRAIN_PATH.mkdir(parents=True, exist_ok=True)
TEST_PATH.mkdir(parents=True, exist_ok=True)

# manually copied images+annotations to Train/Split
# TODO: automate that kind of splitting at some point
