# coding: utf-8

from __future__ import unicode_literals

import logging

from datetime import datetime

from cab.utils import env
from cab.utils import http
from cab.utils import helpers
from cab.utils import datetimes

URL = env.choose({
    'production': 'http://calendar-api.tools.yandex.net',
    'testing': 'http://calendar-api.calcorp-test-back.cmail.yandex.net',
})

API_URL = URL + '/internal'

RESOURCES = {
    'get_events': API_URL + '/get-events',
}

log = logging.getLogger(__name__)


@helpers.timeit
def get_events(auth):
    session = http.get_session()

    # TODO: с учетом таймзоны пользователя
    now = datetime.now()

    query_params = {
        'hideAbsences': 'true',
        'uid': auth.uid,
        'from': datetimes.datetime_isoformat(now),
        'to': datetimes.datetime_isoformat(
            datetimes.shifted_dt(now, days=+90)
        ),
    }

    response = session.get(
        url=RESOURCES['get_events'],
        params=query_params,
    )
    if response.ok and 'events' in response.json():
        return response.json()['events']
    else:
        log.error('Bad calendar response %s' % response.text)
