import re
import subprocess
import sys
from pathlib import Path
import os
output_folder_name = "/quality_test_originals/"
droppedFile = sys.argv[1]
droppedName = Path(droppedFile).name

#get path of script location and remove the tail
head_tail = os.path.split(sys.argv[0])
output_path = head_tail[0]


#skip first part of sys.argv since it points to script location
arguments = sys.argv[1:]

#check if output folder exists, otherwise create it
isExist = os.path.exists(output_path+output_folder_name)
if not isExist:
    os.makedirs(output_path+output_folder_name)

#droppedFile = ["sam_overlord_bluraysource.mkv"]


#lines = "-map 0:v -c:v libx265 -preset slow -crf 22 -x265-params level=51:no-sao=1:bframes=8:psy-rd=1.5:psy-rdoq=1.5:aq-mode=3:ref=6 -pix_fmt yuv420p10le -map 0:a -c:a copy -map 0:s -c:s copy"
org_lineslines = " -map 0:v -c:v copy -map 0:a? -c:a copy -map 0:s? -c:s copy"


number_of_segments=int(input("Number of segments: "))
segment_length=int(input("How long should each segment be(seconds)? "))

for i, file in enumerate(arguments):

    arg_list = 'ffprobe.exe -show_entries format=duration -i "{file}"'.format(file=file)
    print(arg_list)
    cmd = subprocess.Popen(arg_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding='UTF-8')
        
    subprocess_std = cmd.communicate()[0]
   
    print("stdout printing: " , subprocess_std)
    video_duration = [int(s) for s in re.findall(r"[0-9]+", subprocess_std)][0]
    print("video_duration: ", video_duration, "s")
    duration_percent = video_duration / 100
    print(duration_percent)

    time = duration_percent * 15

    skip = ((duration_percent * 90) - (duration_percent* 20))  / (number_of_segments -1)



    
    for i in range(0, number_of_segments):
        basename = os.path.basename(file)
        #args = 'ffmpeg.exe  -i "{file}"  -ss {time} -t {segment_length} {lines} -f matroska "{file}{i}out.mkv"'.format(time=skip*i+time, segment_length=segment_length, file=file, lines=lines, i=i)
        args = 'ffmpeg.exe -ss {time} -i "{file}" -t {segment_length} {org_lineslines} -f matroska "{output_path}{output_folder_name}ORIGINAL_COMP_{i}{basename}"'.format(time=skip*i+time, segment_length=segment_length, file=file, org_lineslines=org_lineslines, output_path=output_path, output_folder_name=output_folder_name, basename=basename, i=i)
        print(args)
        run = subprocess.Popen(args, creationflags=0x00004000)
       
        



    print('\n')
    

input("press enter to exit") 