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

logger = logging.getLogger(__name__)


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

                except KeyboardInterrupt as exc:
                    raise exc

                except IndexError as exc:
                    raise exc

                except Exception as exc:
                    logger.warning('An exception occurred at attempt #{}'.format(try_))
                    logger.warning(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


def get_geobase(geo_id_or_name):
    if isinstance(geo_id_or_name, int):
        condition = 'Id:{}'.format(geo_id_or_name)
    elif isinstance(geo_id_or_name, (str, unicode)):
        condition = u'Runame:{}'.format(geo_id_or_name)

    return geobase_request(condition)


@restartable(retries=10, pause=6)
def geobase_request(condition):
    fields = [
        'Runame', 'Enname', 'ShortName',
        'RunameGenitive', 'RunameDative', 'RunameAccusative', 'RunameInstrumental',
        'RunamePrepositional', 'RunamePreposition'
    ]
    types = [str(type_) for type_ in range(-1, 16)]

    request = requests.post(url='http://geoexport.yandex.ru/',
                            params={'format': 'json',
                                    'types': ','.join(types),
                                    'fields': ','.join(fields),
                                    'equals_search': condition
                                    },
                            timeout=60)
    response = json.loads(request.content)

    return response[0]
