import yt.wrapper as yt_wrapper
from datacloud.dev_utils.logging.logger import get_basic_logger
from datacloud.dev_utils.time import utils as time_utils
from datacloud.log_reader.lib import table_schema

logger = get_basic_logger(__name__)


CLEAN_LOGS_BASE_FOLDER = '//home/x-products/production/services/logs/datacloud_score_api/fast_logs/clean/stream'
TRASH_LOGS_BASE_FOLDER = '//home/x-products/production/services/logs/datacloud_score_api/fast_logs/trash/stream'


class BaseLogWriter(object):
    def __init__(self):
        pass

    def write(self, data):
        """
        data - List[str];  List of json strings
        """
        raise NotImplementedError('`write` is not implemented for BaseLogWriter. Please implement in child class')


class YtLogWriter(BaseLogWriter):
    def __init__(self, yt_client, base_folder, schema=None):
        self._yt_client = yt_client
        self._base_folder = base_folder
        self._schema = schema
        self._log_minutes = 5

    def write(self, data):
        table_path = self._get_table()
        logger.info('LogTable: {}'.format(table_path))
        self._yt_client.write_table(table_path, data)

    def _get_table(self):
        date_time = time_utils.now_floor_str(minutes=self._log_minutes)
        table_path = yt_wrapper.TablePath(
            yt_wrapper.ypath_join(self._base_folder, date_time),
            append=True,
        )
        if not self._yt_client.exists(table_path):
            self._yt_client.create(
                type='table',
                path=table_path,
                recursive=True,
                attributes={'schema': self._schema},
            )
        return table_path


def get_clean_log_writer(yt_client):
    return YtLogWriter(
        yt_client,
        CLEAN_LOGS_BASE_FOLDER,
        table_schema.SCORE_API_LOG_TABLE
    )


def get_trash_log_writer(yt_client):
    return YtLogWriter(
        yt_client,
        TRASH_LOGS_BASE_FOLDER,
        table_schema.SCORE_API_TRASH_LOG_TABLE
    )
