import subprocess
import sys
from pathlib import Path
import os
import re
import math
ffmpeg_location = "D:/FFMPEG/bin/ffmpeg.exe"
ffprobe_location = "D:/FFMPEG/bin/ffprobe.exe"
output_folder_name ="/bulk_convert_out/"

#total filesize allowed in kilobits
total_max_bits = 75000



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)', 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]

#get location of input file
inpath = os.path.split(sys.argv[1])
outpath = inpath[0]


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



for i, file in enumerate(arguments):
   
    arg_list = '{ffprobe_location} -show_entries format=duration -i "{file}"'.format(ffprobe_location=ffprobe_location, 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")


avg_audiorate = video_duration * 68
max_bitrate = (total_max_bits - avg_audiorate) / video_duration
print(max_bitrate)
avg_bitrate = 0.7*max_bitrate
max_bitrate = math.floor(max_bitrate)
avg_bitrate = math.floor(avg_bitrate)
print(avg_audiorate)

print(max_bitrate)
print(avg_bitrate)

basename = Path(file).stem
ffmpeg_args = '{ffmpeg_location} -i "{file}" -c:v libvpx-vp9 -vf "fps=30,scale=1280:-2" -b:v {avg_bitrate}k -maxrate {max_bitrate}k -bufsize 2M -pass 1 -threads 16 -speed 4 -row-mt 1 -tile-rows 2 -tile-columns 6 -f null NUL'.format(ffmpeg_location=ffmpeg_location, file=file, avg_bitrate=avg_bitrate, max_bitrate=max_bitrate)
cmd = subprocess.call(ffmpeg_args)

ffmpeg_args = '{ffmpeg_location} -i "{file}" -c:v libvpx-vp9 -vf "fps=30,scale=1280:-2" -b:v {avg_bitrate}k -maxrate {max_bitrate}k -bufsize 2M -c:a libopus -b:a 68k -pass 2 -threads 16 -speed 4 -row-mt 1 -tile-rows 2 -tile-columns 6 -f webm "{outpath}\{basename}.webm"'.format(ffmpeg_location=ffmpeg_location, file=file, avg_bitrate=avg_bitrate, max_bitrate=max_bitrate,outpath=outpath, basename=basename)
cmd = subprocess.call(ffmpeg_args)

input()