import json
from pathlib import Path
from typing import (
    Dict,
    Union,
)

from edpconfigprovider import ConfigProvider
from edpconfigprovider.exceptions import NoConfigurationException


class JsonConfigProvider(ConfigProvider):
    def __init__(self, json_path: Union[str, Path, Dict]) -> None:
        self.json_path = json_path

    def get_configuration(self) -> dict:
        if isinstance(self.json_path, dict):
            return self.json_path

        if isinstance(self.json_path, str):
            try:
                return json.loads(self.json_path)
            except json.JSONDecodeError:
                pass

        configs_files = [self.json_path]

        if isinstance(self.json_path, str):
            configs_files = self.json_path.split(",")

        json_config = {}
        for config_file in configs_files:
            try:
                file_config = self._read_json_from_file_as_dictionary(config_file)
                json_config.update(file_config)
            except FileNotFoundError:
                raise NoConfigurationException(configuration_name=str(config_file))

        return json_config

    @staticmethod
    def _read_json_from_file_as_dictionary(path: Union[str, Path]) -> dict:
        with open(path, "rb") as f:
            return json.loads(f.read().decode("utf-8"))
