# -*- coding: utf-8 -*-
from os.path import dirname, join
import yaml
from yt import wrapper as yt
from yql.api.v1.client import YqlClient
import xlrd

with open(join(dirname(dirname(__file__)), 'secret.yml')) as fd:
    SECRET = yaml.load(fd)
TOKEN = SECRET['TOKEN']
MD_YT_PATH = '//home/comdep-analytics/public/rewards/manual_rewards'
MD_WB_PATH = join(dirname(__file__), 'manual_rewards.xlsx')

SCHEMA = [
    {'name': 'tp_new', 'type': 'utf8'},
    {'name': 'dt', 'type': 'string'},
    {'name': 'agency_id', 'type': 'int64'},
    {'name': 'agency_name', 'type': 'utf8'},
    {'name': 'scale_name', 'type': 'utf8'},
    {'name': 'discount_type', 'type': 'string'},
    {'name': 'reward_type', 'type': 'string'},
    {'name': 'currency', 'type': 'utf8'},
    {'name': 'cur_rate', 'type': 'double'},
    {'name': 'reward_to_charge_rur', 'type': 'double'},
    {'name': 'reward_to_charge_cur', 'type': 'double'},
    {'name': 'turnover_to_charge_rur', 'type': 'double'},
    {'name': 'turnover_to_charge_cur', 'type': 'double'},
    {'name': 'delkredere_to_charge_rur', 'type': 'double'},
    {'name': 'delkredere_to_charge_cur', 'type': 'double'}
]


def update_manual_data():
    print 'update manual data'
    wb = xlrd.open_workbook(MD_WB_PATH)
    ws = wb.sheet_by_index(0)

    data = []
    for r_num in range(1, ws.nrows):
        row_data = {}
        for col_num, key_ in enumerate(ws.row_values(0)):
            val = ws.cell(r_num, col_num).value
            if key_ == 'agency_id':
                try:
                    val = int(val)
                except ValueError:
                    val = None
            elif key_ in ('cur_rate', 'reward_to_charge_rur', 'reward_to_charge_cur', 'turnover_to_charge_rur',
                          'turnover_to_charge_cur', 'delkredere_to_charge_rur', 'delkredere_to_charge_cur'):
                try:
                    val = float(val)
                except ValueError:
                    val = None
            row_data[key_] = val

        data.append(row_data)

    yt_client = yt.YtClient(token=TOKEN, proxy='hahn')
    with yt_client.Transaction():
        if yt_client.exists(MD_YT_PATH):
            yt_client.remove(MD_YT_PATH)

        yt_client.write_table(yt_client.TablePath(MD_YT_PATH, schema=SCHEMA), data)


def calculate_rewards():
    print 'calculate all rewards'
    with open(join(dirname(__file__), 'yql_query')) as fd:
        yql_query = fd.read().decode('utf-8')

    yql_client = YqlClient(token=TOKEN)
    request = yql_client.query(yql_query, title='YQL: rewards', syntax_version=1)
    request.run()

    result = request.get_results()
    if not result.is_success:
        raise Exception('YQL-result isn\'t success')


if __name__ == '__main__':
    update_manual_data()
    calculate_rewards()
