#!/usr/bin/env python3
"""capture_sequence.py : capture a series of camera images and save to an AVI file
"""
import argparse, time
import numpy as np
import cv2 as cv

#================================================================
def read_one_frame(capture, args):
    """Wait for the first available frame from a camera or file."""
    while True:
        success, frame = capture.read()
        if success:
            if args.verbose:
                print("read image of shape %s" % (str(frame.shape)))
            return frame

#================================================================
def open_video_output(frame, args, frame_rate=30):
    """Open a video output file sized for the given sample frame.  The frame is not written."""

    codec_code = cv.VideoWriter.fourcc(*'MJPG')  # motion JPEG
    frame_width = frame.shape[1]   # cols
    frame_height = frame.shape[0]  # rows
    return cv.VideoWriter(args.out, codec_code, frame_rate, (frame_width, frame_height))

#================================================================
if __name__ == "__main__":
    parser = argparse.ArgumentParser( description = "Save camera frames to a file file.")
    parser.add_argument('--camera', default=0, type=int, help="Select camera by number (default: %(default)s).")
    parser.add_argument('-q','--quiet', action='store_true', help="Run without viewer window or console output.")
    parser.add_argument('--verbose', action='store_true', help='Enable even more detailed logging output.' )
    parser.add_argument('out', default="frames.avi", type=str, nargs='?', help="Specify output AVI file name (default: %(default)s).")
    args = parser.parse_args()

    capture = cv.VideoCapture(args.camera)

    if not capture.isOpened():
        print("Unable to open camera, exiting.")
        exit(1)

    if not args.quiet:
        cv.namedWindow("capture")

    # the output file will be created after the frame size is known
    output = None

    try:
        while True:
            frame = read_one_frame(capture, args)

            if not args.quiet:
                cv.imshow("capture", frame) # display the frame

            if output is None:
                output = open_video_output(frame, args)

            if output is not None:
                output.write(frame)
                if args.verbose:
                    print("wrote frame to file.")

            # If using the GUI, calling waitKey allows the window system event loop to run and update
            # the display.  The waitKey argument is in milliseconds.
            if not args.quiet:
                key = cv.waitKey(33) & 0xFF
                if key == ord('q'):
                    break

    except KeyboardInterrupt:
        print ("User quit.")

    output.release()
    capture.release()
