# -*- coding: utf-8 -*-
#!/usr/bin/env python3
import logging
from yql.api.v1.client import YqlClient
from yql.client.operation import YqlOperationType, YqlOperationShareIdRequest
from client_analytics.weekly_pack_py3.weekly_pack.data import CONFIG, SECRET
from client_analytics.weekly_pack_py3.weekly_pack.data.proceed_data import get_query_text

logger = logging.getLogger(__name__)


def yql_worker(query_name, period):
    logger.info('YQL_WeeklyPack:%s' % query_name)
    worker = YQLWorker('YQL_WeeklyPack:%s' % query_name,
                       get_query_text(query_name).replace('{from_dt}', period['from_dt']).replace('{to_dt}', period['to_dt']))
    worker.run()
    worker.get_result()

    worker.df = worker.df.rename(columns=CONFIG['yql'][query_name]['columns'])

    return worker.df


def get_funnel_table():
    logger.info('YQL_WeeklyPack:funnel')
    worker = YQLWorker('YQL_WeeklyPack:funnel', get_query_text('funnel'), operation_type=YqlOperationType.CLICKHOUSE)
    worker.run()
    worker.get_result()

    worker.df = worker.df.rename(columns=CONFIG['yql']['funnel']['columns'])

    return worker.df


def get_telephony_data():
    logger.info('YQL_WeeklyPack:telephony')
    worker = YQLWorker('YQL_WeeklyPack:telephony', get_query_text('telephony'))
    worker.run()
    worker.get_result()

    worker.dfs[0] = worker.dfs[0].rename(columns={
        'month': 'Месяц',
        'share_spravochnik': 'Справочник',
        'share_metrika': 'Метрика',
        'share_direct': 'Директ'
    })
    setattr(worker.dfs[0], 'from_row', 1)
    setattr(worker.dfs[0], 'from_col', 1)

    worker.dfs[1] = worker.dfs[1].rename(columns={
        'week': 'Неделя',
        'telephonia_client_count': 'Клиенты'
    })
    setattr(worker.dfs[1], 'from_row', 1)
    setattr(worker.dfs[1], 'from_col', 8)

    return worker.dfs


class YQLWorker(object):
    def __init__(self, query_name=None, query=None, operation_type=YqlOperationType.SQLv1):
        super(YQLWorker, self).__init__()
        self.query_name, self.query = query_name, query
        self.operation_type = operation_type

        self.request, self.result = None, None
        self.dfs = []
        self.df = None

    def run(self):
        yql_client = YqlClient(token=SECRET['token'],)
        request = yql_client.query(self.query, title=self.query_name, syntax_version=1)
        request.type = self.operation_type
        request.run()
        self.request = request

        self.result = self.request.get_results()
        if not self.result.is_success:
            raise Exception('%s result isn\'t success!', self.query_name)

    def get_result(self):
        for table in self.result:
            self.dfs.append(table.full_dataframe)
        if len(self.dfs) == 1:
            self.df = self.dfs[0]

    def get_public_url(self):
        share_req = YqlOperationShareIdRequest(self.request.operation_id)
        share_req.run()
        return 'https://yql.yandex-team.ru/Operations/{}'.format(share_req.json)