# -*- coding: utf-8 -*-
import logging
import pandas as pd
from yql.api.v1.client import YqlClient
from yql.client.operation import YqlOperationType, YqlOperationShareIdRequest
from data_worker import SECRET

logger = logging.getLogger(__name__)


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.df = pd.DataFrame()
        logger.info('%s initialized', self.query_name)

    def run(self):
        logger.info('%s run', self.query_name)
        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)

        logger.info('%s successfully completed', self.query_name)

        df = self.result.full_dataframe
        if df is not None:
            if 'date' in df.columns:
                df['date'] = df.date.astype('string')
                df = df.set_index('date')

        self.df = df

    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)
