# -*- coding: utf-8 -*-
import json
import logging
import requests
from time import sleep
from robot import GEO_URL, SECRET, STAFF_URL

logger = logging.getLogger(__name__)


def restartable(retries=4, pause=3):
    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(u'An exception occurred at attempt #{}\n{}'.format(try_, exc.message))
                    logger.warning('Restarting in {} seconds...'.format(pause))
                    sleep(pause)
                    continue

            raise Exception('Max retries has been reached ({})'.format(retries))
        return wrapper
    return decorator


@restartable(retries=3, pause=5)
def make_request(**kwargs):
    request = requests.post(**kwargs)
    if request.status_code != 200:
        raise Exception('request.status_code != 200\n{}'.format(request.text))

    return request


def get_staff_data(issue, lang):
    fields = [
        'name.first.ru', 'name.first.en',
        'name.last.ru', 'name.last.en',
        'official.position.ru', 'official.position.en'
    ]
    try:
        request = make_request(**{
            'url': STAFF_URL + 'persons',
            'params': {'login': issue.createdBy.login,
                       '_fields': ','.join(fields)},
            'headers': {'Authorization': 'OAuth {}'.format(SECRET['token'])},
            'timeout': 60
        })
        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]}

    except Exception as exc:
        logger.error(u'{}: {}'.format(issue.key, exc.message))
        staff_data = {'name': u'{} {}'.format(issue.createdBy.firstName, issue.createdBy.lastName),
                      'position': ''}

    return staff_data


def get_region_names(region_ids, lang):
    region_ids = str(region_ids) if not isinstance(region_ids, unicode) else region_ids
    if not region_ids or region_ids == u'Весь мир':
        if lang == 'ru':
            return u'Весь мир'
        else:
            return u'World'
    elif not all([char.isdigit() or char in [',', ' '] for char in region_ids]):
        return region_ids

    region_ids = [int(region.strip()) for region in region_ids.split(',') if region.strip()]
    region_names = []

    for region_id in region_ids:
        if int(region_id) == 1:
            region_name = u'Москва и область'
        elif int(region_id) == 10174:
            region_name = u'Санкт-Петербург и область'
        else:

            try:
                request = make_request(**{
                    'url': GEO_URL,
                    'params': {'format': 'json',
                               'fields': ','.join(['Id', 'Runame', 'Enname']),
                               'equals_search': 'Id:{}'.format(region_id)},
                    'timeout': 60
                })
                response = json.loads(request.content)
                result = response[0]
                region_name = result['Runame'] if lang == 'ru' else result['Enname']

            except Exception:
                region_name = str(region_id)

        region_names += [region_name]

    if len(region_names) == 1 or len(u', '.join(region_names)) <= 48:
        return u', '.join(region_names)

    else:
        if lang == 'ru':
            return u'Набор регионов'

        else:
            return u'Region selection'
