import subprocess
import sys
from pathlib import Path
import os
from time import sleep
from threading import Thread
import threading
import re
import xml.etree.ElementTree as ET

file="metadata_refresh.txt"

max_threads=int(input("max threads: "))
print(type(max_threads))
i=0
output_folder_name ="/bulk_convert_out/mvkmergedupdated/"

target_bps_per_channel=96000

#audio_stringmap = ""



#droppedFile= ['E:\Shadowplay\Returnal"]
#get path of script location and remove the tail


#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:]
#arguments = droppedFile

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

def read_file(path=""):
    with open(file,'r+') as f: 
        path = f.readlines(1)
        all = f.readlines()
        f.seek(0)
        f.truncate()
        f.writelines(all)
        return path


class CustomThread(Thread):
    # constructor
    def __init__(self, input_file=""):

        # execute the base constructor
        Thread.__init__(self)
        # set a default value
        self.input_file = input_file


    def run(self):

        #sleep(1)
        global i
        file = str(input_file[0])
        file = file.rstrip("\n")


        pathlibname = Path(file)
        show_folder_name = pathlibname.parent.parent.name
        season_folder_name = "/" + pathlibname.parent.name
        isExist = os.path.exists(output_path+output_folder_name+show_folder_name)
        if not isExist:
            os.makedirs(output_path+output_folder_name+show_folder_name)
            sleep(1)
        isExist = os.path.exists(output_path+output_folder_name+show_folder_name+season_folder_name)
        if not isExist:
            os.makedirs(output_path+output_folder_name+show_folder_name+season_folder_name)
            sleep(1)

        sleep(1)


        #os.rename(file, file+"i")
        mkvmerge_input = file
        basename = os.path.basename(file)
        
        mkv_args = 'mkvmerge.exe --output "{output_path}{output_folder_name}/{show_folder_name}/{season_folder_name}/{basename}" "{mkvmerge_input}"'.format(basename=basename, file=file, output_path=output_path,season_folder_name=season_folder_name,show_folder_name=show_folder_name, output_folder_name=output_folder_name, mkvmerge_input=mkvmerge_input)
        
        mkv_run = subprocess.Popen(mkv_args)
        #wait = mkv_run.wait()
        data = mkv_run.wait()
        print("before remove file")
        #os.remove(file+"i")
        basename = os.path.basename(file)
        print(file)
        sleep(1)
        
        if data == 0:
            i=i-1


      
filesize = os.path.getsize(file)
while filesize != 0:
    if i < max_threads:
        global self
        filesize = os.path.getsize(file)
        if filesize != 0:
            input_file = read_file()
            print(input_file)
            t1 = CustomThread(input_file)
            t1.start()
        if filesize == 0:
                while bool(threading.active_count() > 1):
                        print("Finished","out of", )
                        sleep(1)
                        filesize = os.path.getsize(file)
                        if filesize != 0:
                            print("breaking while")
                            break
                filesize = os.path.getsize(file)
                if filesize != 0:
                    print("breaking if")
                    continue
                t1.join()
                print("Completed","out of", "inputs Successfully")
                input("waiting")
                exit()
        
        print("incrementing i in loop")
        i=i+1

    else:
        print("Finished ","out of ")
        sleep(1)
        print("continuing ")
