# importing libraries
import cv2
import numpy as np


drawing = False
point1 = ()
point2 = ()

def mouse_drawing(event, x, y, flags, params):
    global point1, point2, drawing
    if event == cv2.EVENT_LBUTTONDOWN:
        if drawing is False:
            drawing = True
            point1 = (x, y)
        else:
            drawing = False

    elif event == cv2.EVENT_MOUSEMOVE:
        if drawing is True:
            point2 = (x, y)

#xFine = (848, 187, 225, 21.0)
#yFine = (604, 402, 20.5, 276)

xFine = (848, 187, 848 + 225, 187 + 21.0)
yFine = (604, 402, 604 + 20.5, 402 + 276)

frameCountMod = 0
centroidX = [0, 0]
centroidY = [0, 0]

def track(frame, ROI, centroid, update):
    if(update):
        crop = frame[int(ROI[1]):int(ROI[3]), int(ROI[0]):int(ROI[2])]
        crop = cv2.cvtColor(crop, cv2.COLOR_RGB2GRAY)
        crop = cv2.GaussianBlur(crop,(7,7),cv2.BORDER_DEFAULT)

        #ret, thresh = cv2.threshold(crop, 100, 255, cv2.THRESH_OTSU + cv2.THRESH_BINARY)
        ret,thresh = cv2.threshold(crop, 50, 255, 0)
        
        M = cv2.moments(thresh)

        # calculate x,y coordinate of center
        if M["m00"] != 0:
            centroid[0] = int(M["m10"] / M["m00"])
            centroid[1] = int(M["m01"] / M["m00"])
        #else:
        #    cX, cY = 0, 0
        #print(cY)
    cv2.circle(frame, (int(ROI[0]) + centroid[0], int(ROI[1]) + centroid[1]), 3, (0, 255, 0), -1)

cv2.namedWindow("Frame")
cv2.setMouseCallback("Frame", mouse_drawing)
  
# Create a VideoCapture object and read from input file
cap = cv2.VideoCapture("/home/mwinter/Portfolio/a_history_of_the_domino_problem/a_history_of_the_domino_problem_source/recs/a_history_of_the_domino_problem_final_documentation_hq.mp4")
cap.set(cv2.CAP_PROP_POS_FRAMES, 10000)

# Check if camera opened successfully
if (cap.isOpened()== False):
    print("Error opening video file")
  
frameCountMod = 0
centroidX = [0, 0]
centroidY = [0, 0]

# Read until video is completed
while(cap.isOpened()):
      
    # Capture frame-by-frame
    ret, frame = cap.read()
    if ret == True:
    # Display the resulting frame

        if(frameCountMod == 0):
            track(frame, xFine, centroidX, True)
            track(frame, yFine, centroidY, True)
            xPos = (centroidX[0] / xFine[2]) * 2 - 1
            yPos = (centroidY[1] / yFine[3]) * 2 - 1
        else:
            track(frame, xFine, centroidX, False)
            track(frame, yFine, centroidY, False)

        frameCountMod = (frameCountMod + 1) % 3

        cv2.rectangle(frame, (int(xFine[0]), int(xFine[1])), (int(xFine[2]),int(xFine[3])), (0, 255, 0))
        cv2.rectangle(frame, (int(yFine[0]), int(yFine[1])), (int(yFine[2]),int(yFine[3])), (0, 255, 0))

        if point1 and point2:
            #cv2.rectangle(frame, point1, point2, (0, 255, 0))
            xFine = (point1[0], point1[1], point2[0], point2[1])
            
        cv2.imshow("Frame", frame)

          
    # Press Q on keyboard to exit
        if cv2.waitKey(25) & 0xFF == ord('q'):
            break
  
# Break the loop
    else:
        break
  
# When everything done, release
# the video capture object
cap.release()
  
# Closes all the frames
cv2.destroyAllWindows()