from threading import current_thread
from typing import (
    Dict,
    TypeVar,
)

from edpconfigprovider import ConfigProvider
from edpconfigprovider.builder import ProviderBuilder

T = TypeVar("T")


class ByTenantDynamicConfigProvider(ConfigProvider):
    def __init__(
        self,
        provider_builder: ProviderBuilder,
    ) -> None:
        self.provider_builder = provider_builder

        self._built_config_providers: Dict[str, ConfigProvider] = {}

    def get_configuration(self) -> dict:
        thread = current_thread()
        tenant_name = getattr(thread, "_edp_tenant_name", None)
        if tenant_name is None:
            tenant_name = getattr(thread, "_edp_context_name", None)
        if tenant_name is not None:
            tenant_name = tenant_name.split(".")[0]
        return self._build_config(tenant_name)

    def _build_config(self, tenant_name) -> dict:
        if tenant_name is None:
            return {}

        if tenant_name not in self._built_config_providers:
            self._built_config_providers[tenant_name] = self.provider_builder.build_provider(tenant_name=tenant_name)

        return {
            "name": tenant_name,
            "value": self._built_config_providers[tenant_name].get_configuration(),
        }
