# coding: utf-8

"""
All bicycles and reusable code snippets in one place
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals

import six
import math
import time
import pytz
import random
from datetime import datetime

from requests.exceptions import ConnectionError

GEO_LOCATIONS = frozenset({'MAN', 'MSK', 'SAS', 'VLA'})
DC_LOCATIONS = frozenset({'IVA', 'MAN', 'MYT', 'SAS', 'VLA'})


def wait_minute():
    time.sleep(60)


def linear_delay_generator(n):
    """
    Provides not more than fixed % delay overhead
    and generates O(log T) requests
    """
    delay = float(n)
    multiplier = 1.05
    while True:
        delay *= multiplier
        yield int(delay)


def get_current_timestamp():
    return int(time.time())


def random_hexadecimal_string(length):
    """
    :param length: desired number of hexadecimal chars in string (>0)
    """
    return '{1:0>{0}x}'.format(length, random.getrandbits(length * 4))


def connection_error(exception):
    return isinstance(exception, ConnectionError)


def round_up(n, decimals=0):
    multiplier = 10 ** decimals
    return math.ceil(n * multiplier) / multiplier


def get_datetime_timestamp(dt):
    if six.PY3:
        return dt.timestamp()
    else:
        if dt.tzinfo is None:
            return time.mktime(dt.timetuple())
        else:
            return int((dt - datetime(1970, 1, 1, tzinfo=pytz.utc)).total_seconds())
