import yaml
import pprint
import os 
import json


def load_from_yaml(fname):
    with open(fname, encoding='utf-8') as f:
        base_config = yaml.safe_load(f)
    return base_config

def load_from_json(fname):
    with open(fname, "r", encoding='utf-8') as f:
        base_config = json.load(f)
    return base_config

class Cfg(dict):
    def __init__(self, config_dict):
        super(Cfg, self).__init__(**config_dict)
        self.__dict__ = self

    @staticmethod
    def load_config_from_file(fname, download_base=False):
        if not os.path.exists(fname):
            raise FileNotFoundError("Not found config at {}".format(fname))
        if fname.endswith(".yaml") or fname.endswith(".yml"):
            return Cfg(load_from_yaml(fname))
        elif fname.endswith(".json"):
            return Cfg(load_from_json(fname))
        else:
            raise Exception(f"{fname} not supported")


    def save(self, fname):
        with open(fname, 'w', encoding='utf-8') as outfile:
            yaml.dump(dict(self), outfile, default_flow_style=False, allow_unicode=True)

    # @property
    def pretty_text(self):
        return pprint.PrettyPrinter().pprint(self)

