#! /usr/bin/env python
# -*- coding: utf-8 -*-

from main.settings import db
import random
from moviepy.editor import VideoFileClip, concatenate, cvsecs

# Get entry in list where given key has given value
def findwhere (key, value, list):
    for entry in list:
        if entry[key] == value:
            return entry

# Returns clip for given video file, from start time till end time
def get_clip (video, start, end, padding = .1):
    return VideoFileClip(video).subclip(start - padding, end + padding)

# Returns all the sentences with the given word
def sentences_with(word):
    return [sentence for sentence in db.sentences.find({'words.word': word})]

# selects one of the selected sentences
def random_sentence_with(word):
    return random.choice(sentences_with(word))

# Returns all the words found
def get_words (word):
    return [findwhere('word', word, sentence['words']) for sentence in sentences_with(word)]

# randoms one of the found words
def get_word(word, sentence):
    return findwhere('word', word, sentence['words'])

# Returns a subclip for a word in the given sentence
def get_word_clip(word, sentence):
    word = get_word(word, sentence)
    return get_clip(sentence['filename'], word['start'], word['end'])

def random_word_clip(word):
    return get_word_clip(word, random_sentence_with(word))

if __name__ == '__main__':
    output = 'output/sentence.mp4'
    sentence = ['the', 'american', 'people']
    clips = [random_word_clip(word) for word in sentence] # excecute 'random_word_clip(word)' for every 'word' in 'sentence' + append it to the list 'clips'
    final = concatenate(clips) # Concatenate given subclips into new VideoFileClip
    final.to_videofile(output) # Export generated clips into video