from matplotlib import pyplot as plt
import numpy as np
import os
import statistics
import cv2
from collections import Counter



def analyzeSectionThree(nameID, fps, staticPartCircle, staticPartImage, staticPartText, xLE, yLE, xRE, yRE, xLEcm, yLEcm, xREcm, yREcm):   
    if not os.path.exists("Outputs"):
        os.makedirs("Outputs")
        
    if not os.path.exists("Outputs/" + nameID):
        os.makedirs("Outputs/" + nameID)
        
    if not os.path.exists("Outputs/" + nameID + "/SectionThree"):
        os.makedirs("Outputs/" + nameID + "/SectionThree")
    
    
    ### X AND Y COORDINATES OF CIRCLE NO GRID FOR EACH EYE
    staticCircleXLE = xLE[staticPartCircle[0]:staticPartCircle[1]]
    staticCircleYLE = yLE[staticPartCircle[0]:staticPartCircle[1]]
    staticCircleXRE = xRE[staticPartCircle[0]:staticPartCircle[1]]
    staticCircleYRE = yRE[staticPartCircle[0]:staticPartCircle[1]]
    
    halfSizeRange = (len(staticCircleXLE) + 1) // 2
    
    circleXLE = staticCircleXLE[:halfSizeRange]
    circleXLEGrid = staticCircleXLE[halfSizeRange:]
    
    circleYLE = staticCircleYLE[:halfSizeRange]
    circleYLEGrid = staticCircleYLE[halfSizeRange:]
    
    circleXRE = staticCircleXRE[:halfSizeRange]
    circleXREGrid = staticCircleXRE[halfSizeRange:]
    
    circleYRE = staticCircleYRE[:halfSizeRange]
    circleYREGrid = staticCircleYRE[halfSizeRange:]
    
    varianceXLE = statistics.variance(circleXLE)
    varianceYLE = statistics.variance(circleYLE)
    varianceXLEGrid = statistics.variance(circleXLEGrid)
    varianceYLEGrid = statistics.variance(circleYLEGrid)
    
    varianceXRE = statistics.variance(circleXRE)
    varianceYRE = statistics.variance(circleYRE)
    varianceXREGrid = statistics.variance(circleXREGrid)
    varianceYREGrid = statistics.variance(circleYREGrid)
    
    print('Variance X No Grid for Left Eye:', varianceXLE)
    print('Variance X Grid for Left Eye:', varianceXLEGrid)
    print('Variance Y No Grid for Left Eye:', varianceYLE)
    print('Variance Y Grid for Left Eye:', varianceYLEGrid)
    
    print('Variance X No Grid for Right Eye:', varianceXRE)
    print('Variance X Grid for Right Eye:', varianceXREGrid)
    print('Variance Y No Grid for Right Eye:', varianceYRE)
    print('Variance Y Grid for Right Eye:', varianceYREGrid)
    
    plt.plot(circleYLE, circleXLE)
    plt.xlabel('Y')
    plt.ylabel('X')
    plt.title('X and Y coordinates of Static Circle No Grid of Left Pupil Center')
    plt.savefig("Outputs/" + nameID + "/SectionThree" + "/" + "circleXLE_circleYLE.pdf")
    plt.show()
    
    plt.plot(circleYLEGrid, circleXLEGrid)
    plt.xlabel('Y')
    plt.ylabel('X')
    plt.title('X and Y coordinates of Static Circle Grid of Left Pupil Center')
    plt.savefig("Outputs/" + nameID + "/SectionThree" + "/" + "circleXLEGrid_circleYLEGrid.pdf")
    plt.show()
    
    plt.plot(circleYRE, circleXRE)
    plt.xlabel('Y')
    plt.ylabel('X')
    plt.title('X and Y coordinates of Static Circle No Grid of Right Pupil Center')
    plt.savefig("Outputs/" + nameID + "/SectionThree" + "/" + "circleXRE_circleYRE.pdf")
    plt.show()
    
    plt.plot(circleYREGrid, circleXREGrid)
    plt.xlabel('Y')
    plt.ylabel('X')
    plt.title('X and Y coordinates of Static Circle Grid of Right Pupil Center')
    plt.savefig("Outputs/" + nameID + "/SectionThree" + "/" + "circleXREGrid_circleYREGrid.pdf")
    plt.show()
    
    ### Static Part - Image
    
    # staticImageXLE = xLE[staticPartCircle[0]:staticPartCircle[1]]
    # staticImageYLE = yLE[staticPartCircle[0]:staticPartCircle[1]]
    # staticImageXRE = xRE[staticPartCircle[0]:staticPartCircle[1]]
    # staticImageYRE = yRE[staticPartCircle[0]:staticPartCircle[1]]
    
    
    
    
    
    
    
    staticImageXLE = xLE[staticPartCircle[0]:staticPartCircle[1]]
    staticImageYLE = yLE[staticPartCircle[0]:staticPartCircle[1]]
    staticImageXRE = xREcm[staticPartText[0]:staticPartText[1]]
    staticImageYRE = yREcm[staticPartText[0]:staticPartText[1]]
    
    plt.plot(staticImageXLE, staticImageYLE)
    plt.xlabel('X')
    plt.ylabel('Y')
    plt.title('X and Y coordinates of Static Image of Left Eye')
    plt.savefig("Outputs/" + nameID + "/SectionThree" + "/" + "staticImage_LeftEye.pdf")
    plt.show()
    
    plt.plot(staticImageXRE, staticImageYRE)
    plt.xlabel('X')
    plt.ylabel('Y')
    plt.title('X and Y coordinates of Static Image of Right Eye')
    plt.savefig("Outputs/" + nameID + "/SectionThree" + "/" + "staticImage_RightEye.pdf")
    plt.show()
    
    image = plt.imread('C:/Users/Michal/Documents/Uni/Ing/Diplomka/code/monaLisa.png')
    
    matica = np.zeros([510,660,4])
    matica[9:499, 114:444] = image
    
    # Load the image
    image = cv2.imread('C:/Users/Michal/Documents/Uni/Ing/Diplomka/code/monaLisa.png')
    overlay = np.zeros_like(image, dtype=np.uint8)

    opacity = 0.2
    image = cv2.addWeighted(image, opacity, overlay, 1 - opacity, 0)

    # Get the dimensions of the image
    height, width, _ = image.shape
    
    # Create a new blank image with double width and height + 20
    new_width = width * 2
    new_height = height + 20
    new_image = np.zeros((new_height, new_width, 3), dtype=np.uint8)
    
    # Calculate the center position to place the image
    center_x = new_width // 2
    center_y = (new_height) // 2
    
    # Calculate the start and end positions for placing the image
    start_x = center_x - width // 2
    end_x = start_x + width
    start_y = center_y - height // 2
    end_y = start_y + height
    
    # Copy the image onto the new blank image
    new_image[start_y:end_y, start_x:end_x] = image
    
    yCoords = []
    xCoords = []
    
    for x, y in zip(staticImageXLE, staticImageYLE):
        localX = 70.7 - (x - 120.5)
        localY = y - 101.5
        xCoords.append(int((localX)*new_width/70.5) + 160) 
        yCoords.append(int((localY/2)*new_height/32) - 80)
    
    # Create tuples from the arrays
    tuples = list(zip(xCoords, yCoords))
    
    # Count the occurrences of the tuples
    counts = Counter(tuples)
    
      # Define a colormap (e.g., Jet colormap)
    # colormap = cv2.COLORMAP_JET
    
    # Normalize the counts to the range [0, 1]
    # normalized_counts = np.array(counts) / max(counts)
    
    # Map the normalized counts to colormap values
    # color_values = (normalized_counts * 255).astype(np.uint8)
    
    # Create an image with the colormap
    # colored_image = cv2.applyColorMap(color_values, colormap)
    r = 2
    # Print the counts
    for tuple_item, count in counts.items():
        localX = (tuple_item[0])
        localY = (tuple_item[1])
        #value = np.array([255, 0, 0], dtype=np.float64)
        #new_image [localY-r:localY+r,localX-r:localX+r] =  new_image [localY-r:localY+r,localX-r:localX+r] * 0.5 + 0.5 * (0, 0, 255)
        #cv2.addWeighted(new_image [localY-r:localY+r,localX-r:localX+r], 1 - 0.5, value, 0.5, 0,new_image [localY-r:localY+r,localX-r:localX+r])
        red_intensity = count*100  # Use the count as the red channel intensity value
        new_image[localY-r:localY+r, localX-r:localX+r, 2] = red_intensity  # Set red intensity value


        
    # Display the result
    cv2.imshow('Centered Image', new_image)
    cv2.imwrite("SakmarovaHeatMap.png", new_image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    
    
    
    ### Static Part - Text
    
    staticTextXLE = xLEcm[staticPartText[0]:staticPartText[1]]
    staticTextYLE = yLEcm[staticPartText[0]:staticPartText[1]]
    staticTextXRE = xREcm[staticPartText[0]:staticPartText[1]]
    staticTextYRE = yREcm[staticPartText[0]:staticPartText[1]]
    
    time = range(len(staticTextXLE))
    time = [x / fps for x in time]
    
    plt.plot(time, staticTextXLE)
    plt.xlabel('Time')
    plt.ylabel('X')
    plt.title('X coordinate of Left Pupil Center in Static Part Text')
    plt.savefig("Outputs/" + nameID + "/SectionThree" + "/" + "staticTextXLE.pdf")
    plt.show()
    
    plt.plot(staticTextXLE, staticTextYLE)
    plt.xlabel('X')
    plt.ylabel('Y')
    plt.title('X coordinate of Left Pupil Center in Static Part Text')
    plt.savefig("Outputs/" + nameID + "/SectionThree" + "/" + "staticTextXLE.pdf")
    plt.show()
    