"""
Combine images to video
"""
from cv2 import VideoWriter, VideoWriter_fourcc, imread, resize
import glob, os, argparse


argparser = argparse.ArgumentParser()
argparser.add_argument("--fps", type=float, default=29.0)
argparser.add_argument("-o", "--output", type=str, help="Specify output video name", default="test.mp4")
argparser.add_argument("-e", "--extension", type=str, help="indicate image file extension", default="jpg")
argparser.add_argument("-d", "--datadir", type=str, help="Specify data location")


def make_video(images, outvid=None, fps=5, size=None,
               is_color=True, format="XVID"):
    """
    Create a video from a list of images.

    @param      outvid      output video
    @param      images      list of images to use in the video
    @param      fps         frame per second
    @param      size        size of each frame
    @param      is_color    color
    @param      format      see http://www.fourcc.org/codecs.php
    @return                 see http://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_gui/py_video_display/py_video_display.html

    The function relies on http://opencv-python-tutroals.readthedocs.org/en/latest/.
    By default, the video will have the size of the first image.
    It will resize every image to this size before adding them to the video.
    """
    fourcc = VideoWriter_fourcc(*format)
    vid = None

    if outvid == None:
        outvid = './out.mp4'

    for image in images:
        if not os.path.exists(image):
            raise FileNotFoundError(image)
        img = imread(image)

        if vid is None:

            if size is None:
                size = (img.shape[1], img.shape[0])

            vid = VideoWriter(outvid, fourcc, fps, size, is_color)
        if size[0] != img.shape[1] and size[1] != img.shape[0]:
            img = resize(img, size)
        vid.write(img)
    vid.release()
    return vid

if __name__ == "__main__":
    config = argparser.parse_args()

    if config.datadir == None:
        raise ValueError("[!] Dataset not found!")

    imgs = glob.glob(os.path.join(config.datadir, '*.{}'.format(config.extension)))
    make_video(sorted(imgs), config.output, fps=config.fps)
