# coding: utf-8


import logging

import datetime
import urllib3
from django.conf import settings
from django.utils import timezone
from idm.utils import http

log = logging.getLogger(__name__)


def get_hired_employees():
    """Список сотрудников, которые скоро будут в штате
        https://st.yandex-team.ru/STAFF-5417
        30 - заявка подтверждена руководителем.
        40 - подготовка рабочего места.
        50 - добавлен на стафф.
    """
    now = timezone.now()

    max_retries = urllib3.Retry(
        total=settings.IDM_NEWHIRE_RETRIES_COUNT,
        backoff_factor=settings.IDM_NEWHIRE_BACKOFF_FACTOR,
        status_forcelist=settings.IDM_NEWHIRE_STATUS_FORCELIST,
    )

    try:
        resp = http.get(
            settings.IDM_NEWHIRE_URL,
            headers={'Authorization': 'OAuth %s' % settings.IDM_STAFF_OAUTH_TOKEN},
            max_retries=max_retries,
            use_client_certificate=False,
        )
        offers = resp.json()
        new_offers = []
        for offer in offers:
            if offer['state'] not in settings.IDM_NEWHIRE_STATES:
                continue
            join_at = datetime.datetime.strptime(offer['join_at'], '%Y-%m-%d').replace(tzinfo=timezone.utc)
            before_timedelta = datetime.timedelta(days=settings.IDM_NEWHIRE_FRESHNESS_DAYS_BEFORE)
            after_timedelta = datetime.timedelta(days=settings.IDM_NEWHIRE_FRESHNESS_DAYS_AFTER)
            if now - join_at > before_timedelta:
                continue
            if join_at - now > after_timedelta:
                continue
            new_offers.append(offer)

        return [user['username'] for user in new_offers]

    except (http.RequestException, KeyError, ValueError):
        log.exception('Cannot get hired employees from hire %s', url)
        raise
