#! /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 parse, pprint, tag, tokenize, tag, parsetree
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.")
# p.add_argument("--collection", default=None, help="write the name of the collection from the database you want to use as source, written in between quotes.")
args = p.parse_args()

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

# if args.collection == None:
#     args.collection = "sentences"


# 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 tag
def sentences_with(tag):
    return [sentence for sentence in db.sentences.find({'words.tag': tag})]

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

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

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

# Returns a subclip for a tag in the given sentence
def get_tag_clip(tag, sentence):
    tag = get_tag(tag, sentence)
    return get_clip(sentence['filename'], tag['start'], tag['end'])

def random_tag_clip(tag):
    return get_tag_clip(tag, random_sentence_with(tag))



# list to store all tags
sentencePoswords = []

for tag, pos in tag(args.text):
    sentencePoswords.append(pos)

print args.text
print sentencePoswords

if __name__ == '__main__':
    output = 'output/tag-generated-video.mp4'
    clips = [random_tag_clip(tag) for tag in sentencePoswords] # excecute 'random_tag_clip(tag)' for every 'tag' 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