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

from robot import SECRET, STAFF_URL

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_data(login, lang):
    fields = [
        'name.first.ru', 'name.first.en',
        'name.last.ru', 'name.last.en',
        'official.position.ru', 'official.position.en'
    ]
    request = requests.post(
        url=STAFF_URL + 'persons',
        params={
            'login': login,
            '_fields': ','.join(fields),
        },
        headers={'Authorization': 'OAuth {}'.format(SECRET['token'])},
        timeout=60
    )
    if request.status_code != 200:
        logger.error('{}: request.status_code != 200\n{}'.format(STAFF_URL, request.text))
        staff_data = {'name': '', 'position': ''}

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

        staff_data = {
            'name': u'{} {}'.format(result['name']['first'][lang], result['name']['last'][lang]),
            'position': result['official']['position'][lang]
        }

    return staff_data
