import cv2
import numpy as np
from scipy import ndimage
from matplotlib import pyplot as plt

import pupilDetection
import pupilSize

def pupilDetectionTracking(videoPath, leftEye, rightEye, fps):
    cap = cv2.VideoCapture(videoPath)

    xLE = []
    xRE = []
    yLE = []
    yRE = []
    
    pupilSizeLE = []
    pupilSizeRE = []
    
    while True:
        ret, frame = cap.read()
        
        if not ret:
            break
        
        widthEyeArea = 150
        heigthEyeArea = 100
        
        roiLE = frame[leftEye[1] - heigthEyeArea : leftEye[1] + heigthEyeArea, leftEye[0] - widthEyeArea : leftEye[0] + widthEyeArea]
        roiRE = frame[rightEye[1] - heigthEyeArea : rightEye[1] + heigthEyeArea, rightEye[0] - widthEyeArea : rightEye[0] + widthEyeArea]

        grayLE = cv2.cvtColor(roiLE, cv2.COLOR_BGR2GRAY)
        grayRE = cv2.cvtColor(roiRE, cv2.COLOR_BGR2GRAY)
        
        
        ## Pupil Detection
        
        pupilSizeLE, pupilSizeRE = pupilDetection.pupilDetection(roiLE, roiRE, grayLE, grayRE, pupilSizeLE, pupilSizeRE, xLE, yLE, xRE, yRE)
        
        # print("Number of pixels in pupil:", count)
        # cv2.imshow("Detected Pupil - Left Eye", roiLE)
        # cv2.imwrite("SakmarovaROILE.png", roiLE)
        # cv2.imshow("Detected Pupil - Right Eye", roiRE)
        # cv2.imwrite("SakmarovaROIRE.png", roiRE)
        
        # if cv2.waitKey(0) & 0xFF == ord('n'):
        #     continue
        
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
        
    cap.release()
    cv2.destroyAllWindows()
    
    time = range(len(pupilSizeLE))
    time = [x / fps for x in time]
    
    plt.plot(time, pupilSizeLE)
    plt.xlabel('time [seconds]')
    plt.ylabel('Pupil Size [pixel count]')
    plt.title('Pupil Size over Time of the Left Eye')
    plt.savefig("PupilSizeLE_Time.pdf")
    plt.show()
    
    plt.plot(time, pupilSizeRE)
    plt.xlabel('time [seconds]')
    plt.ylabel('Pupil Size [pixel count]')
    plt.title('Pupil Size over Time of the Right Eye')
    plt.savefig("PupilSizeRE_Time.pdf")
    plt.show()
    
    return xLE, yLE, xRE, yRE, pupilSizeLE, pupilSizeRE