#!/usr/bin/env python3


from os import system, _exit,name
from subprocess import call
import sys
from os import listdir, path
from os.path import isfile, join, basename, normpath, relpath, dirname, abspath, isdir,splitext
import pathlib
from glob import glob



menu = """
 
    FFenmass
    CLI Utility to encode and recreate directories with ffmpeg.
    Version : 0.2.3
                

"""

# Check if the Directory exists, if not make it
def checkmake_dir(directory: str):
    return pathlib.Path(directory).mkdir(parents=True, exist_ok=True)

# Return All file objects from a directory tree
def get_all_media_files_in_dir(inpath: str):
    filesonly = []
    for item in list(glob(inpath + '/**/*', recursive=True)):
        if isfile(item):
            filesonly.append(item)

    return filesonly



# Change the full input path root path to match the output root path
def outfile_path(fullfilepath: str,inpath:str, outpath: str):
    fullout = fullfilepath.replace(inpath,outpath)
    checkmake_dir(dirname(fullout))
    return splitext(fullout)[0]



# Check if a string is a directory
def dir_path(string):
    if isdir(string):
        return string
    else:
        return False


if __name__ == '__main__':
    try:
        system('cls' if name == 'nt' else 'clear')
        print(menu)
        args = ['ffmpeg','-hide_banner' ,'-y']+sys.argv[1:]


        #Checking if input exists
        try:
            inpath = args[args.index('-i') + 1]
        except ValueError:
            print('ERROR : Could not catch -i argument')
            try:
                sys.exit(0)
            except SystemExit:
                _exit(0)



        #Checking if input/output is valid directory
        outpath = args[len(args)-1:][0]
        if dir_path(inpath):
            pass
        else:
            print('Input is not a valid directory!')
            try:
                sys.exit(0)
            except SystemExit:
                _exit(0)
        if dir_path(outpath):
            pass
        else:
            print('Output is not a directory!')
            try:
                sys.exit(0)
            except SystemExit:
                _exit(0)

        #Checking if extension is provided
        try:
            extension = args[args.index('-f') + 1]
        except ValueError:
            print('ERROR : Could not catch -f argument')
            try:
                sys.exit(0)
            except SystemExit:
                _exit(0)


        #Getting all paths and files    
        inputfiles = get_all_media_files_in_dir(inpath=inpath)
        print(
            f'Grabbed {len(inputfiles)} media files to encode.')
        counter = 0



        #Main Program Loop
        for file in inputfiles:
            args[args.index('-i') + 1] = file
            print(
                    f"Processed : {counter}/{len(inputfiles)}")
            print(
                    f"Currently Processing  : {basename(file)}")
            print("\n\n\n")

            args[-1] = outfile_path(fullfilepath=file,inpath=inpath ,outpath=outpath)
            
            try:
                call(args)
            except KeyboardInterrupt:
                print('Keyboard Exception, exiting.')
                break
            
            
            counter += 1

            # Clearing everything and reprinting
            system('cls' if name == 'nt' else 'clear')
            print(menu)

            
    
    
    #Keyboard Interrupt
    except KeyboardInterrupt:
        print('Keyboard Exception, exiting.')
        try:
            sys.exit(0)
        except SystemExit:
            _exit(0)

