# -*- coding: utf-8 -*-
import time
from datetime import datetime
from datacloud.dev_utils.time.patterns import FMT_DATE_YM
from datacloud.dev_utils.solomon.solomon_utils import post_sensors_to_solomon

SOLOMON_PROJECT = 'datacloud'
SOLOMON_CLUSTER = {
    'qloud_logs': 'real_money',
    'fast_logs': 'fast_logs_money'
}
DAILY_SERVICE = 'money-daily'
MONTHLY_SERVICE = 'money-monthly'


def get_sensor(partner_id, contract_id, year, month, day, column, value, **kwargs):
    dt = datetime(year=year, month=month, day=day)

    return {
        'labels': {
            'partner_id': partner_id,
            'contract_id': contract_id,
            'column': column,
            'period': dt.strftime(FMT_DATE_YM)
        },
        'ts': time.mktime(dt.timetuple()),
        'value': value
    }


def get_daily_sensors(partner_id, contract_id, year, month, day, money, money_no_min, **kwargs):
    money_sensor = get_sensor(
        partner_id=partner_id, contract_id=contract_id, year=year,
        month=month, day=day, column='money', value=money)

    no_min_sensor = get_sensor(
        partner_id=partner_id, contract_id=contract_id, year=year,
        month=month, day=day, column='money_no_min', value=money_no_min)

    return [money_sensor, no_min_sensor]


def get_monthly_sensors(partner_id, contract_id, year, month, day, **kwargs):
    sensors = []
    for column in ('money', 'bill', 'hit', 'hit_unique', 'has_score', 'no_score',
                   'requests', 'answers', 'timeout', 'timeout_share'):
        sensors.append(get_sensor(
            partner_id=partner_id,
            contract_id=contract_id,
            year=year,
            month=month,
            day=day,
            column=column,
            value=kwargs[column]
        ))

    return sensors


def post_results(yt_client, table_to_post, money_log_table, sensors_function,
                 service, log_type):
    sensors = []
    for row in yt_client.read_table(table_to_post):
        money_log_table.add_record(**row)
        sensors.extend(sensors_function(**row))

    post_sensors_to_solomon(
        SOLOMON_PROJECT,
        SOLOMON_CLUSTER[log_type],
        service,
        sensors
    )
