#!/usr/bin/env python
# file video.py
# author Florent Guiotte <florent.guiotte@uhb.fr>
# version 0.0
# date 31 mai 2019
"""Abstract

doc.
"""

from panflute import *
from pathlib import Path

video_format = ('mp4', 'webm')

def create_thumbnail(fname):
    thumbnail = fname.parent / (fname.stem + '.png')
    if not thumbnail.is_file():
        shell('ffmpeg -i {} -frames 1 {}'.format(fname, thumbnail))
    return thumbnail

def video(elem, doc):
    if isinstance(elem, Para) and isinstance(elem.content[0], Image):
        img = elem.content[0]
        url = Path(img.url)
        if img.url.endswith(video_format):
            if not url.is_file():
                debug('video.py: {} does not exist.'.format(url))
                return []
            thumbnail = create_thumbnail(url)
            shell('touch yay.txt')
            if doc.format == 'beamer':
                return convert_text('\inlineMovie[loop&autostart]{{{}}}{{{}}}{{}}'.format(img.url, thumbnail))
            if doc.format == 'revealjs':

                return convert_text('<video autoplay loop> \
                    <source data-src="{}" type="video/{}" /> \
                </video>'.format(url, url.suffix.strip('.')))

def main(doc=None):
    return run_filter(video, doc=doc)

if __name__ == '__main__':
    main()
