# -*- coding: utf-8 -*-
from datacloud.dev_utils.yt import yt_config_table
from datacloud.dev_utils.logging.logger import get_basic_logger
from datacloud.dev_utils.time.utils import assert_date_str

logger = get_basic_logger(__name__)
DEFAULT_PATH = '//home/x-products/production/datacloud/stability/scores_and_features_PSI/psi_scores_all_new_temporary'


__all__ = [
    'ScoresPsiTable'
]


class ScoresPsiTable(yt_config_table.ConfigTable):
    def __init__(self, table_path=DEFAULT_PATH, yt_client=None):
        schema = [
            {'name': 'score_name', 'type': 'string', 'sort_order': 'ascending'},
            {'name': 'date', 'type': 'string', 'sort_order': 'ascending'},
            {'name': 'score_type', 'type': 'string', 'sort_order': 'ascending'},
            {'name': 'input_table', 'type': 'string'},
            {'name': 'reference_table', 'type': 'string'},
            {'name': 'PSI', 'type': 'any'},
            {'name': 'norm_hist', 'type': 'any'},
            {'name': 'table_size', 'type': 'int64'},
            {'name': 'is_reference', 'type': 'boolean'},
            {'name': 'additional', 'type': 'any'},
        ]

        super(ScoresPsiTable, self).__init__(
            table_path, schema, yt_client
        )

    def add_record(self, score_name, date, score_type, input_table, reference_table,
                   PSI, norm_hist, table_size, is_reference, additional=None):

        assert_date_str(date)
        additional = additional or {}

        record = {
            'score_name': score_name,
            'date': date,
            'score_type': score_type,
            'input_table': input_table,
            'reference_table': reference_table,
            'PSI': PSI,
            'norm_hist': norm_hist,
            'table_size': table_size,
            'is_reference': is_reference,
            'additional': additional
        }
        self.insert_records([record])

    def get_reference_rows(self, score_name, score_type):
        return self.get_records_by_params({
            'score_name': score_name,
            'score_type': score_type,
            'is_reference': True
        })

    def get_record(self, score_name, date, score_type):
        return self.get_record_by_params({
            'score_name': score_name,
            'date': date,
            'score_type': score_type
        })

    def mark_as_reference(self, score_name, date, score_type):
        rec = self.get_record_by_params({
            'score_name': score_name,
            'date': date,
            'score_type': score_type
        })
        rec['is_reference'] = True
        self.insert_records([rec])
