# coding: utf-8

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

import logging
import datetime

from saas.library.python.common_functions import get_current_timestamp
from saas.library.python.yasm.constants import YasmPeriod, AGGREGATE_LAG
from saas.library.python.common_functions import get_datetime_timestamp
from requests.exceptions import ConnectionError, ReadTimeout
from retry.api import retry

LOGGER = logging.getLogger(__name__)


def get_interval_begin_end(period, interval_begin, interval_end):
    if isinstance(interval_end, datetime.datetime):
        interval_end = get_datetime_timestamp(interval_end)
    if isinstance(interval_begin, datetime.datetime):
        interval_begin = get_datetime_timestamp(interval_begin)

    if isinstance(period, YasmPeriod):
        period = period
    else:
        period = YasmPeriod(period)

    interval_end_limit = get_current_timestamp() - AGGREGATE_LAG[period]
    if interval_end > interval_end_limit:
        interval_end = interval_end_limit
        LOGGER.warning('Interval end adjusted to {}'.format(interval_end_limit))

    if interval_end < interval_begin:
        raise ValueError(
            'Interval end must be greater than interval begin, but interval_begin={}, interval_end={}'.format(
                interval_begin, interval_end
            )
        )

    return period, interval_begin, interval_end


def timestamps_range(interval_begin, interval_end, period=YasmPeriod.five_seconds):
    period, interval_begin, interval_end = get_interval_begin_end(period, interval_begin, interval_end)
    return [int(el) for el in range(interval_begin, interval_end+1, 5)]


# TODO move this function to YasmSignalGroup class
@retry((ConnectionError, ReadTimeout), tries=5, delay=2)
def get_golovan_snapshot(url, description='', text='', **params):
    request_to_ap_template = "{}://s.{}&{}"
    params['static'] = 1
    request = request_to_ap_template.format(url.split("://")[0], url.split("://")[1], "&".join(["{}={}".format(key, params[key]) for key in params]))
    import requests
    sess = requests.Session()
    picture_url = sess.get(request, timeout=5).url
    return "{}(({} {}))".format(text, url, picture_url)
