from datacloud.dev_utils.ydb.lib.core.ydb_table import YdbTable
import ydb


class ScorePathTable(YdbTable):
    def __init__(self, ydb_manager, database, table):
        super(ScorePathTable, self).__init__(ydb_manager, database, table)

    def create(self):
        with self._init_session() as session:
            session.create_table(
                self.full_table_path,
                ydb.TableDescription()
                .with_column(ydb.Column('internal_score_name', ydb.OptionalType(ydb.DataType.String)))
                .with_column(ydb.Column('score_path', ydb.OptionalType(ydb.DataType.String)))
                .with_primary_key('internal_score_name')
            )

    def get_one(self, record):
        query_params = {
            '$internal_score_name': record.internal_score_name
        }
        return self._get_one(query_params)

    def get(self, record):
        query_params = {
            '$internal_score_name': record.internal_score_name
        }
        for rec in self._get(query_params):
            yield rec

    class Record(object):
        __slots__ = ('internal_score_name', 'score_path')

        def __init__(self, internal_score_name, score_path=None):
            self.internal_score_name = internal_score_name
            self.score_path = score_path

        def __str__(self):
            return '({}: {})'.format(self.internal_score_name, self.score_path)

        def __repr__(self):
            return self.__str__()

        def __eq__(self, other):
            return self.internal_score_name == other.internal_score_name and self.score_path == other.score_path

    _insert_request = """
        PRAGMA TablePathPrefix("{database}");

        DECLARE $records AS "List<Struct<
        internal_score_name: String,
        score_path: String>>";

        REPLACE INTO [{table}]
        SELECT
            internal_score_name,
            score_path
        FROM AS_TABLE($records);
    """

    _select_request = """
        PRAGMA TablePathPrefix("{database}");

        DECLARE $internal_score_name AS String;

        SELECT *
        FROM [{table}]
        WHERE internal_score_name = $internal_score_name;
    """
