import re
import subprocess
import sys
from pathlib import Path
import os
output_folder_name = "\mkvmerge_out\\"
regex_subtitle = re.compile("Stream #0:\d+(\(\w*\))?: Subtitle:.*")
regex_audio = re.compile("Stream #0:\d+(\(\w*\))?: Audio:.*")
nr_files = 0
files_processed = []
audio_list = []
sub_list = []
droppedFile = sys.argv[1]
droppedName = Path(droppedFile).name
originalfiles = sys.orig_argv[2:]



#droppedFile= ['X:\\test\\longpathtest\\longerpathlongerpathlongerpathlongerpathlongerpathlongerpathlongerpath\\longpathlongpathlongpathlongpathlongpathlongpathlongpathlongpathlongpathlongpathlongpathlongpathlongpathlongpath\\fourteen\\[Kira-Fansub]_Choujuushin Gravion_Episode 06_(BD 1280x960 h264 JP AAC EN AAC) [E7D92968].mkv', '', ' X:\\test\\longpathtest\\longerpathlongerpathlongerpathlongerpathlongerpathlongerpathlongerpath\\longpathlongpathlongpathlongpathlongpathlongpathlongpathlongpathlongpathlongpathlongpathlongpathlongpathlongpath\\fourteen\\[Kira-Fansub]_Choujuushin Gravion_Episode 09_(BD 1280x960 h264 JP AAC EN AAC) [A2727604].mkv']
#originalfiles = droppedFile


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




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

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



for file in listed:
    basename = os.path.basename(file)

    arg_list = 'mkvmerge.exe --output "{output_path}{output_folder_name}{basename}" "{file}"'.format(file=file, output_path=output_path, output_folder_name=output_folder_name, basename=basename)
    print(arg_list)
    subprocess.run(arg_list)
    nr_files = nr_files+1
    files_processed.append(file)


print("Number of files processed: ", nr_files)
print(*files_processed, sep='\n')
input("press enter to exit") 
