"""
*************************************************************************
// Example program using OpenCV library
//      python >3.7 - OpenCV 4.5
// @file	e3.py
// @author Luis M. Jimenez
// @date 2022
//
// @brief Course: Computer Vision (1782)
// Dept. of Systems Engineering and Automation
// Automation, Robotics and Computer Vision Lab (ARVC)
// http://arvc.umh.es
// University Miguel Hernandez
//
// @note Description:
//	- This example captures images from a camera, shows them in a window and...
//  - Enables a handler for mouse events
//  - Saves window image on leftmouse+Shift click
//  - Saves window image on Space bar or F5 keystroke
//
*************************************************************************
"""

# Import libraries
import cv2 as cv
import numpy as np
import argparse

# -----------------------------------------
# Functions
# -----------------------------------------
"""
//----------------------------------------------------------------------
// Mouse events handler  for image window
//----------------------------------------------------------------------
// event:	event type sent to the handler ->  cv.EVENT_MOUSEMOVE,
//          cv.EVENT_LBUTTONDOWN, cv.EVENT_LBUTTONUP, cv.EVENT_LBUTTONDBLCLK,
//          cv.EVENT_RBUTTONDOWN, cv.EVENT_RBUTTONUP, cv.EVENT_RBUTTONDBLCLK,
//          cv.EVENT_MBUTTONDOWN, cv.EVENT_MBUTTONUP, cv.EVENT_MBUTTONDBLCLK,
//          cv.EVENT_MOUSEWHEEL, cv.EVENT_MOUSEHWHEEL
// x:	X-coordinate position of the mouse in window
// y:	Y-coordinate position of the mouse in window
// flags: aditional flags sent to the handler ->
//          cv.EVENT_FLAG_SHIFTKEY, cv.EVENT_FLAG_CTRLKEY, cv.EVENT_FLAG_ALTKEY,
//          cv.EVENT_FLAG_LBUTTON, cv.EVENT_FLAG_RBUTTON, cv.EVENT_FLAG_MBUTTON, 
// param: set in cv.SetMouseCallback
//----------------------------------------------------------------------
"""
def onMouse(event, x, y, flags, param):
    global ID_FILE, capture  # global variables used in the mouse handler
    print(f"{event=}, {x=}, {y=}, {flags=}, {param=}")

    # on click left mouse button and SHIFT key, saves image
    if event==cv.EVENT_LBUTTONDOWN and (flags & cv.EVENT_FLAG_SHIFTKEY):
        filename = f"Image{ID_FILE}.jpg"
        print(f"Saving image window in file: {filename}")
        cv.imwrite(filename, capture)   # save window image
        ID_FILE += 1


# -----------------------------------------
# Global variables
# -----------------------------------------
WINDOW_CAMERA1 = '(W1) Camera 1'   # window id
CAMERA_ID = 0	                   # default camera
KEY_F5 = 7602176                   # F5 unicode key code
ID_FILE = 1                        # filename id

# check command line parameters (camera id)
parser = argparse.ArgumentParser(description='OpenCV example: captures images from a camera')
parser.add_argument('-c', dest='cameraID', type=int, default=CAMERA_ID, metavar='id', help='camera id')
CAMERA_ID = parser.parse_args().cameraID

# -----------------------------------------
# Put here the code to Initialize objets
# -----------------------------------------

# Open camera object
camera = cv.VideoCapture(CAMERA_ID)
if not camera.isOpened():
    print("you need to connect a camera, sorry.")
    exit()

# Getting camera resolution
cameraWidth = int(camera.get(cv.CAP_PROP_FRAME_WIDTH))
cameraHeight = int(camera.get(cv.CAP_PROP_FRAME_HEIGHT))

# Creating visualization windows
cv.namedWindow(WINDOW_CAMERA1, cv.WINDOW_AUTOSIZE)

# Setting Mouse Handler
cv.setMouseCallback(WINDOW_CAMERA1, onMouse)

print(f"Capturing images from camera {CAMERA_ID} ({cameraWidth},{cameraHeight})")
print("...Hit F5 or Space bar to capture and save the image")
print("...Hit q/Q/Esc to exit.")

# -----------------------------------------
# Main Loop
# while there are images ...
# -----------------------------------------
while True:
    # Capture frame-by-frame
    ret, capture = camera.read()

    # if frame is read correctly ret is True
    if not ret:
        print("Can't receive frame (stream end?). Exiting ...")
        break
    # -----------------------------------------
    # Put your image processing code here
    # -----------------------------------------


    # -----------------------------------------
    # Put your visualization code here
    # -----------------------------------------
    cv.imshow(WINDOW_CAMERA1, capture)     # Display the resulting frame

    # check keystroke to exit (image window must be on focus)
    key = cv.pollKey()
    if key == ord('q') or key == ord('Q') or key == 27:
        break
    elif key == KEY_F5 or key == ord(' '):
        filename = f"Image{ID_FILE}.jpg"
        print(f"Saving image window in file: {filename}")
        cv.imwrite(filename, capture)   # save window image
        ID_FILE += 1

# End while (main loop)

# -----------------------------------------
# free windows and camera resources
# -----------------------------------------
cv.destroyAllWindows()
if camera.isOpened():  camera.release()
