#!/usr/bin/env python

import sys
import ffmpeg

class Video:
    def __init__(self,max_width=1024,*args,**kwargs):
        super(Video,self).__init__()
        self.args = args
        self.kwargs = kwargs
        self.file = kwargs['file']
        self.out = 'thumbnail.jpg'
        self.max_width = max_width

    def gen_video_thumbnail(self):
        """
        Generate a thumbnail from a video
        """

        probe = ffmpeg.probe(self.file)
        time = float(probe['streams'][0]['duration']) // 5
        v_width = probe['streams'][0]['width']
        width = self.set_width(v_width)

        try:
            (
                ffmpeg.input(self.file, ss=time)
                .filter('scale', width, -1)
                .output(self.out, vframes=1)
                .overwrite_output()
                .run(capture_stdout=True, capture_stderr=True)
            )
        except ffmpeg.Error as e:
            print(e.stderr.decode(), file=sys.stderr)

        return self.out

    def set_width(self,v_width):
        if v_width > self.max_width:
            width = self.max_width
        else:
            width = v_width

        return width