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

from main.settings import db
import random
from moviepy.editor import VideoFileClip, concatenate, cvsecs
from pattern.en import tokenize, parse
from argparse import ArgumentParser

# set arguments for the script
p = ArgumentParser("This generator creates a videofile based on the structure of the input sentence.")
p.add_argument("--text", default=None, help="the input text, a sentence, written in between quotes.")
args = p.parse_args()

if args.text == None:
    args.text = "I eat pizza with a fork."

# 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/words-generated-video.mp4'
    tokenizedSentence = tokenize(args.text)[0].split()

    print args.text
    print tokenizedSentence

    clips = [random_word_clip(word) for word in tokenizedSentence] # 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, fps=24) # Export generated clips into video