import subprocess
import sys
from pathlib import Path
import os
import re
from ffmpeg_quality_metrics import FfmpegQualityMetrics


output_folder_name ="/bulk_convert_out/"

droppedFile = sys.argv[1]
droppedName = Path(droppedFile).name
originalfiles = sys.orig_argv[2:]

#long path shenanigans 
joined = (' '.join(originalfiles))
re.sub (' +', ' ', joined)
listed = re.split(r'(.+?mkv|.+?mov|.+?mp4)', joined)
listed = list(filter(None, listed))
listed = [i.lstrip() for i in listed]

#print(droppedName)

#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)


print("input 0: ", listed[0])
print("input 1: ", listed[1])
x=int(input("select reference file: "))
ref= listed.pop(x)
print(listed)
print("selected reference file is: ", ref)
print("1: vmaf_v0.6.1.json")
print("2: vmaf_4k_v0.6.1.json")
x=int(input("select vmaf model: "))

if x == 1:
    scale = '"scale=1920:1080"'
    model = "vmaf_v0.6.1"
else:
    scale = '"scale=3840:2160"'
    model = "vmaf_4k_v0.6.1"


#basename = os.path.basename(file)
#
args = 'ffmpeg-quality-metrics "{distorted}" "{reference}" -p -m psnr ssim vmaf -t 12 --vmaf-threads 12 '.format(distorted=listed[0],reference=ref,scale=scale, model=model)
#print(args)
subprocess.run(args)

#ffqm =FfmpegQualityMetrics(ref, listed[0])
#metrics = ffqm.calculate(["ssim", "psnr"])
#print(metrics.keys)
#print(sum([frame["ssim_y"] for frame in metrics["ssim"]]) / len(metrics["ssim"]))
#print(ffqm.get_global_stats()["ssim"]["ssim_y"]["average"])

k=input("press close to exit") 