import os
from . import res

def extract_encoding_time_percentages(am):
    extract = {}

    for preset in am.keys():
        if not preset in extract.keys():
            extract[preset] = {}

        for crf in am[preset].keys():
            if not crf in extract[preset].keys():
                extract[preset][crf] = {}

            extract[preset][crf]["mean"] = am[preset][crf]["encoding_time_percentage"]["mean"]
            extract[preset][crf]["median"] = am[preset][crf]["encoding_time_percentage"]["median"]

    return extract

def extract_filesize_percentages(am):
    extract = {}

    for preset in am.keys():
        if not preset in extract.keys():
            extract[preset] = {}

        for crf in am[preset].keys():
            if not crf in extract[preset].keys():
                extract[preset][crf] = {}

            extract[preset][crf]["mean"] = am[preset][crf]["filesize_percentage"]["mean"]
            extract[preset][crf]["median"] = am[preset][crf]["filesize_percentage"]["median"]

    return extract

def extract_vmaf_scores(am):
    extract = {}

    for preset in am.keys():
        if not preset in extract.keys():
            extract[preset] = {}

        for crf in am[preset].keys():
            if not crf in extract[preset].keys():
                extract[preset][crf] = {}

            extract[preset][crf]["mean"] = am[preset][crf]["vmaf_score"]["mean"]
            extract[preset][crf]["median"] = am[preset][crf]["vmaf_score"]["median"]

    return extract

def start_workflow():
    res.bootstrap_folder_structure()

    aggregated_metrics = res.read_dict_from_json_file(
        os.path.join(
            res.get_path_results_aggregations(),
            res.get_filename_results_aggregations_av1()
        )
    )

    # encoding time percentages
    res.save_diagram_bars(
        res.generate_diagram_bars(
            extract_encoding_time_percentages(aggregated_metrics),
            "AV1 encoding time percentages by Preset and CRF",
            "Percent of the encoding time of HEVC"
        ),
        os.path.join(
            res.get_path_results_diagrams(),
            f'av1_encoding_time_percentages.png'
        )
    )

    # filesize percentages
    res.save_diagram_bars(
        res.generate_diagram_bars(
            extract_filesize_percentages(aggregated_metrics),
            "AV1 filesize percentages by Preset and CRF",
            "Percent of the filesize of HEVC"
        ),
        os.path.join(
            res.get_path_results_diagrams(),
            f'av1_filesize_percentages.png'
        )
    )

    # vmaf scores
    res.save_diagram_bars(
        res.generate_diagram_bars(
            extract_vmaf_scores(aggregated_metrics),
            "AV1 VMAF scores by Preset and CRF",
            "VMAF Score"
        ),
        os.path.join(
            res.get_path_results_diagrams(),
            f'av1_vmaf_scores.png'
        )
    )
