from ast import arguments
import re, subprocess, sys, os, shutil
from pathlib import Path


output_folder_name = "/temp/"
droppedFile = sys.argv[1]
droppedName = Path(droppedFile).name

#droppedFile = ['test_source.mkv']

#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:]

number_of_ss=int(input("Number of ss: "))
print(number_of_ss)
#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)



#run ffprobe to get duration of input file, then get appropriate timestamps out of it
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]
   
   #use search instead of findall, no need to add it in a list
   #int(re.search(r"[0-9]+", subprocces_std)[0])
   #convert result to int
    video_duration = [int(s) for s in re.findall(r"[0-9]+", subprocess_std)][0]
    duration_percent = video_duration / 100
    time = duration_percent * 15
    skip = ((duration_percent * 90) - (duration_percent* 15)) / (number_of_ss -1)

    #run ffmpeg to get screenshots and previously determined timestamps

    for i in range(0, number_of_ss):
        
        basename = os.path.basename(file)
        args = 'ffmpeg.exe -ss {time} -i "{file}" -frames:v 1 -q:v 1 "{output_path}{output_folder_name}{basename}{i}.jpg"'.format(time=skip*i+time, file=file, output_path=output_path, output_folder_name=output_folder_name, basename=basename, i=i)
        print(args)
        subprocess.call(args)


#Find all new images in the output folder
img = os.listdir(output_path+output_folder_name)

#run getnative on all images created
for each in img:
    args = 'py -3 -m getnative --show-plot-gui "{output_path}{output_folder_name}{each}" '.format(output_path=output_path,output_folder_name=output_folder_name, each=each)
    print(args)

    subprocess.call(args)


#clean the trash files generated
lwi = os.listdir(output_path)
for item in lwi:
    if item.endswith(".lwi"):
        os.remove(os.path.join(output_path, item))
shutil.rmtree(output_path+"/temp")
shutil.rmtree(output_path+"/results")

input("press enter to exit") 
