# -*- coding: utf-8 -*-
import logging
from time import sleep
import requests
import json
from yt import wrapper as yt

from robot import STAFF_URL, TABLES_YT_PATH, TOKEN

logger = logging.getLogger(__name__)


def restartable(retries=1, pause=0):
    def decorator(func):
        def wrapper(*args, **kwargs):
            for try_ in xrange(retries):
                try:
                    return func(*args, **kwargs)

                except KeyboardInterrupt as kb_exception:
                    raise kb_exception

                except Exception as exc:
                    logger.warning('An exception occurred at attempt #{}'.format(try_))
                    logger.error(exc.message)
                    logger.warning('Restarting in {} seconds...'.format(pause))
                    sleep(pause)
                    continue
            logger.error('Max retries has been reached ({})'.format(retries))
            return None
        return wrapper
    return decorator


@restartable(retries=3, pause=10)
def get_staff_position(login):
    request = requests.post(
        url=STAFF_URL + 'persons',
        params={
            'login': login,
            '_fields': 'official.position.ru',
        },
        headers={'Authorization': 'OAuth {}'.format(TOKEN)},
        timeout=60
    )
    if request.status_code != 200:
        raise Exception('{}: request.status_code != 200\n{}'.format(STAFF_URL, request.text))

    response = json.loads(request.content)
    result = response['result'][0]

    return result['official']['position']['ru']


def read_yt_tables():
    yt_client = yt.YtClient(token=TOKEN, proxy='hahn')

    valid_values = dict()
    for table_name, key in zip(['Last_period_Brands', 'Last_period_Mediagroups'], ['Brand', 'MediaGroup']):
        table_values = list(
            yt_client.read_table(TABLES_YT_PATH + table_name, format="<encode_utf8=%false>json")
        )
        valid_values[key] = [row[key] for row in table_values]

    return valid_values['Brand'], valid_values['MediaGroup']


def get_period_from_yt():
    yt_client = yt.YtClient(token=TOKEN, proxy='hahn')
    table_name = 'Last_period_Dates'

    table_values = list(
        yt_client.read_table(TABLES_YT_PATH + table_name, format="<encode_utf8=%false>json")
    )[0]

    return table_values['MinMonth'], table_values['MaxMonth']
