# -*- coding: utf-8 -*
from yt.wrapper import ypath_join
from datacloud.dev_utils.yt import yt_config_table

PRIVATE_ROOT = '//home/x-products/production/datacloud/money'
PUBLIC_ROOT = '//home/x-products/public/money'
TYPE_TO_PATH = {
    ('fast_logs', 'daily'): 'fast_logs/money_log',
    ('fast_logs', 'monthly'): 'fast_logs/money_monthly_log',
    ('qloud_logs', 'daily'): 'qloud_logs/money_log',
    ('qloud_logs', 'monthly'): 'qloud_logs/money_monthly_log'
}
STATIC_SUFFIX = '_static'


class MoneyLogTable(yt_config_table.ConfigTable):
    def __init__(self, log_type='qloud_logs', period_type='daily', yt_client=None):
        path_suffix = TYPE_TO_PATH[(log_type, period_type)]
        self._public_path = ypath_join(PUBLIC_ROOT, path_suffix) + STATIC_SUFFIX
        schema = [
            {'name': 'partner_id', 'type': 'string', 'sort_order': 'ascending'},
            {'name': 'contract_id', 'type': 'string', 'sort_order': 'ascending'},
            {'name': 'year', 'type': 'uint16', 'sort_order': 'ascending'},
            {'name': 'month', 'type': 'uint8', 'sort_order': 'ascending'},
            {'name': 'day', 'type': 'uint8', 'sort_order': 'ascending'},
            {'name': 'money', 'type': 'double'},
            {'name': 'additional', 'type': 'any'}
        ]
        super(MoneyLogTable, self).__init__(
            ypath_join(PRIVATE_ROOT, path_suffix), schema, yt_client
        )

    def add_record(self, partner_id, contract_id, year, month, day, money, **kwargs):
        record = {
            'partner_id': partner_id,
            'contract_id': contract_id,
            'year': year,
            'month': month,
            'day': day,
            'money': money,
            'additional': kwargs
        }
        self.insert_records([record])

    def get_contract_id(self, partner_id, score_name, first_month, last_month=None):
        return self.get_record_by_params({
            'partner_id': partner_id,
            'score_name': score_name,
            'first_month': first_month,
            'last_month': last_month
        })

    def make_static_copy(self):
        self._yt_client.run_sort(
            self.table_path,
            self._public_path,
            sort_by=[c['name'] for c in self.schema if 'sort_order' in c]
        )
