from yt.wrapper.default_config import get_config_from_env

from intranet.trip.src.config import settings
from intranet.trip.src.lib.yt.api import write_rows
from intranet.trip.src.lib.yt.dataclasses import RegistryRow
from intranet.trip.src.lib.yt.exceptions import YtError


class YtGateway:
    """
    Инкапсуляция работы с YT
    """
    def __init__(
        self,
        proxy: str,
        prefix: str,
        tabular_data_format: str,
    ):
        self._config = get_config_from_env()
        self._config['prefix'] = prefix
        self._config['tabular_data_format'] = tabular_data_format
        self._config['proxy']['url'] = proxy
        self._config['yamr_mode']['create_recursive'] = True
        # must be defined in the inheritor
        self._row_type = None

    async def write_rows(self, table: str, rows: list):
        """ all data in table will be replaced """
        if not self._row_type:
            raise YtError(message='Row type must be defined')
        await write_rows(
            rows=rows,
            table=table,
            row_type=self._row_type,
            config=self._config,
        )


class YtRegistry(YtGateway):
    """
    Запись реестров в YT
    """
    def __init__(
        self,
        proxy: str = settings.YT_PROXY,
        prefix: str = settings.YT_PREFIX,
        tabular_data_format: str = 'yson',
    ):
        super().__init__(proxy, prefix, tabular_data_format)
        self._row_type = RegistryRow
