# -*- coding: utf-8 -*-
import os
from yt.wrapper.config import get_command_param
import yt.wrapper as yt_wrapper
from yql.api.v1.client import YqlClient
from datacloud.dev_utils.logging.logger import get_basic_logger

logger = get_basic_logger(__name__)

__all__ = [
    'YqlExecutionException',
    'create_yql_client',
    'execute_yql',
]


class YqlExecutionException(Exception):
    pass


def create_yql_client(yt_client=None, db=None, token=None):
    """
    Creates YQL client from given YT client or based on given cluster and token
    """
    assert yt_client or (db and token)
    yt_cluster = db or yt_client.config['proxy']['url']
    token = token or yt_client.config['token']
    if token is None:
        token_path = yt_client.config["token_path"]
        if token_path is None:
            token_path = os.path.join(os.path.expanduser("~"), ".yt/token")
        with open(token_path, 'r') as token_file:
            token = token_file.read().strip()
    return YqlClient(db=yt_cluster, token=token)


# TODO: Вынести отсюда owners
def execute_yql(query, yql_client=None, yt_client=None, transaction_id=None,
                params=None, set_owners=True, urls2attach=None,
                syntax_version=1, title=None):
    """
    Excecutes YQL query in given transaction or in transcation
    from `yt_client` or in transaction from global yt client
    """
    urls2attach = urls2attach or []
    assert yql_client is not None or yt_client is not None
    if yql_client is None:
        yql_client = create_yql_client(yt_client=yt_client)
    if params is not None:
        query = query % params
    if set_owners:
        owners = ['re9ulusv', 'nryzhikov', 'penguin-diver']
        query = ('PRAGMA yt.Owners = "%s";\n' % ','.join(owners)) + query
    transaction_id = transaction_id or get_command_param('transaction_id', yt_client)
    if syntax_version is None:
        syntax_version = 0

    request = yql_client.query(query, syntax_version=syntax_version, title=title)
    for url, name in urls2attach:
        request.attach_url(url, name)
    logger.debug('Executing YQLv%s query: [%s]', syntax_version, query)
    request.run(transaction_id=transaction_id)
    logger.info('Executing YQL query with id [%s] by %s',
                request.operation_id, request.json.get('username'))
    results = request.get_results()
    if not request.is_success:
        raise YqlExecutionException((request.status, list(map(str, request.errors))))
    return list(results)


def get_yql_token():
    yql_token = os.environ.get('YQL_TOKEN')
    if not yql_token:
        yql_token = yt_wrapper.config['token']
    assert yql_token, 'Please provide YQL token'

    return yql_token
