import os
import json
import string
import random
import subprocess
import multiprocessing

def local_clip(filename, start_time, duration, output_filename, output_directory):
    end_time = start_time + duration
    command = ['ffmpeg',
               '-i', '"%s"' % filename,
               '-ss', str(start_time),
               '-t', str(end_time - start_time),
               '-c:v', 'libx264', 
               '-threads', '1',
               '-async', '1',
               '-loglevel', 'panic',
               os.path.join(output_directory,output_filename)]
    command = ' '.join(command)

    print(command)

    try:
        output = subprocess.check_output(command, shell=True,
                                         stderr=subprocess.STDOUT)
    except subprocess.CalledProcessError as err:
        print (err.output)
        return err.output


def wrapper(clip_name, clip):
    input_directory = 'mlb_dataset/input'
    output_directory = 'mlb_dataset/output'
    os.makedirs(output_directory)
    duration = clip['end']-clip['start'] + 5
    filename = clip['url'].split('=')[-1]
    #print(filename)
    print(clip)
    local_clip(os.path.join(input_directory,filename+'.mp4'), clip['start'], duration, clip_name+'.mp4', output_directory)
    return 0

# def wrapper_2(clip):
#     input_directory = 'mlb_dataset/input'
#     output_directory = 'mlb_dataset/output'
#     clip_name = clip[0]
#     clip = clip[1]
#     print(clip)
#     duration = clip['end']-clip['start']
#     filename = clip['url'].split('=')[-1]
#     local_clip(os.path.join(input_directory,filename+'.mkv'), clip['start'], duration, clip_name+'.mp4', output_directory)
#     return 0
    

with open('data/mlb-youtube-segmented.json', 'r') as f:
    data = json.load(f)
    # pool = multiprocessing.Pool(processes=4)
   #x print(data.keys())
    for k in data.keys():
        wrapper(k, data[k])
    # pool.map(wrapper_2, [[k,data[k]] for k in data.keys()])
    
