## this module is used to read and write yaml files

# debugging
import logging

# yaml
import yaml

# file and paths manipulation
import os
from pathlib import Path


def read_yaml(path_yaml, what=None):
    path_yaml = Path(path_yaml)
    with open(path_yaml) as file:
        dict_yaml = yaml.load(file, Loader=yaml.FullLoader)
    if what is None:
        return dict_yaml
    else:
        if isinstance(what, list):
            output = []
            for what_single in what:
                output.extend(dict_yaml[what_single])
            return output
        elif isinstance(what, str):
            output = dict_yaml[what]
            return output
        else:
            logging.critical(
                "Wrong type passed into read_yaml method - use None,list or str"
            )


def save_yaml(path_yaml, dict_yaml):
    path_yaml = Path(path_yaml)

    with open(path_yaml, "w") as file:
        yaml.dump(dict_yaml, file, sort_keys=False)
    print(f"Yaml file saved to {path_yaml}")


def modify_yaml(path_yaml, what_dict):
    dict_yaml = read_yaml(path_yaml)

    for what_exactly in list(what_dict.keys()):
        dict_yaml[what_exactly] = what_dict[what_exactly]

    save_yaml(path_yaml, dict_yaml)


def batch_modify_yaml(path_folder_wyamls, what_dict):
    path_to_search_in = Path(path_folder_wyamls)
    list_of_files = []
    for dirpath, dirnames, filenames in os.walk(path_to_search_in, 1):
        for filename in [f for f in filenames if f.endswith(".yaml")]:
            list_of_files.append(os.path.join(dirpath, filename))
    for path_yaml in list_of_files:
        modify_yaml(path_yaml, what_dict)
