import cv2
from matplotlib import pyplot as plt

def pupilDetection(roiLE, roiRE, grayLE, grayRE, pupilSizeLE, pupilSizeRE, xLE, yLE, xRE, yRE):
    gaussianLE = cv2.GaussianBlur(grayLE, (11, 11), 0)
    gaussianRE = cv2.GaussianBlur(grayRE, (11, 11), 0)
    
    medianLE = cv2.medianBlur(gaussianLE, 3)
    medianRE = cv2.medianBlur(gaussianRE, 3)

    min_intensityLE = medianLE.min()
    min_intensityRE = medianRE.min()
    # grayEquLE = cv2.equalizeHist(medianLE)
    # grayEquRE = cv2.equalizeHist(medianRE)
    
    _, thresholdLE = cv2.threshold(medianLE, min_intensityLE + 10, 255, cv2.THRESH_BINARY_INV)
    contoursLE, _ = cv2.findContours(thresholdLE, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    contoursLE = sorted(contoursLE, key=lambda x: cv2.contourArea(x), reverse=True)

    for cnt in contoursLE:
        (x, y, w, h) = cv2.boundingRect(cnt)
        pupilCenterLE = [x + w // 2, y + h // 2]
        
        xLE.append(pupilCenterLE[0])
        yLE.append(pupilCenterLE[1])
        
        cv2.circle(roiLE, (pupilCenterLE[0], pupilCenterLE[1]), int((h)/2), (0, 0, 255), 2)
        break
        
    _, thresholdRE = cv2.threshold(medianRE, min_intensityRE + 10, 255, cv2.THRESH_BINARY_INV)
    contoursRE, _ = cv2.findContours(thresholdRE, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    contoursRE = sorted(contoursRE, key=lambda x: cv2.contourArea(x), reverse=True)

    for cnt in contoursRE:
        (x, y, w, h) = cv2.boundingRect(cnt)
        pupilCenterRE = [x + w // 2, y + h // 2]
        
        xRE.append(pupilCenterRE[0])
        yRE.append(pupilCenterRE[1])
        
        cv2.circle(roiRE, (pupilCenterRE[0], pupilCenterRE[1]), int((h)/2), (0, 0, 255), 2)
        break
    
    pupilSizeLE.append(cv2.countNonZero(thresholdLE))
    pupilSizeRE.append(cv2.countNonZero(thresholdRE))

    # print("Pupil Size of Left Eye", pupilSizeLE)
    # print("Pupil Size of Right Eye:", pupilSizeRE)
    
    cv2.imshow("Detected Pupil - Left Eye", roiLE)
    # cv2.imwrite("SakmarovaPupilLE.png", roiLE)
    cv2.imshow("Detected Pupil - Right Eye", roiRE)
    # cv2.imwrite("SakmarovaPupilRE.png", roiRE)
    
    # if cv2.waitKey(0) & 0xFF == ord('n'):
    #     continue
    
    return pupilSizeLE, pupilSizeRE