import os
import subprocess
import time
from . import res

DEFAULT_BITDEPTH_HEVC = 10
DEFAULT_CRF_HEVC = 21
DEFAULT_PARAMS_HEVC = "aq-mode=1:qcomp=0.7:vbv-bufsize=9000:vbv-maxrate=9000:no-sao=1:no-strong-intra-smoothing=1:keyint=240:min-keyint=24"
DEFAULT_PIX_FMT_HEVC = "yuv420p10le"
DEFAULT_PRESET_HEVC = "slow"

def get_encoding_command_hevc(f):
    filenameSample = os.path.splitext(os.path.basename(f))[0]
    filenameEncode = ".".join(
        [
            filenameSample,
            'HEVC',
            '10Bit',
            'Preset',
            f'{DEFAULT_PRESET_HEVC}',
            'CRF',
            f'{DEFAULT_CRF_HEVC}',
            'mkv'
        ]
    )
    filepathEncode = os.path.join(res.get_path_data_encodes_hevc(), filenameEncode)

    cmd_parts = [
        'ffmpeg',
        f'-i "{f}"',
        '-an',
        '-c:v libx265',
        f'-preset {DEFAULT_PRESET_HEVC}',
        f'-crf {DEFAULT_CRF_HEVC}',
        f'-x265-params "{DEFAULT_PARAMS_HEVC}"',
        f'-pix_fmt {DEFAULT_PIX_FMT_HEVC}',
        '-y',
        f'"{filepathEncode}"'
    ]
    
    return " ".join(cmd_parts)

def start_workflow():
    res.bootstrap_folder_structure()

    path_results_encoding_time_hevc_json = os.path.join(
        res.get_path_results_encoding_time(),
        res.get_filename_results_encoding_time_hevc()
    )
    results_encoding_time_hevc = res.read_dict_from_json_file(
        path_results_encoding_time_hevc_json
    )

    for f in res.get_all_sample_files():
        filename = os.path.splitext(os.path.basename(f))[0]
        if filename in results_encoding_time_hevc.keys():
            continue

        time_start = time.time()
        subprocess.run(
            get_encoding_command_hevc(f),
            shell=True,
            check=True
        )
        time_encoding = round(time.time() - time_start)
        
        results_encoding_time_hevc[filename] = time_encoding

        res.write_dict_to_json_file(
            path_results_encoding_time_hevc_json,
            results_encoding_time_hevc
        )
        