import logging

from django.conf import settings

from staff.lib import requests, tvm2

from staff.lib.decorators import (
    responding_json,
    available_for_external,
)

from django.views.decorators.http import require_GET

logger = logging.getLogger(__name__)


@responding_json
@available_for_external
@require_GET
def goals(request, login):
    tvm_ticket = request.yauser.raw_user_ticket

    try:
        goals_data = get_person_goals(
            goals_host=settings.GOALS_HOST,
            login=login,
            tvm_ticket=tvm_ticket,
        )
    except requests.Timeout as exc:
        logger.exception(
            f'Goals request timeouted: {exc}',
        )

        return {}
    except requests.HTTPError as exc:
        logger.exception(
            f'Request for goals of "{login}" failed with status code: {exc}'
        )

        return {}

    return {'target': {'goals': goals_data}}


def get_person_goals(goals_host, login, tvm_ticket):
    goals_request_timeout = (1, 1.5, 3)

    url = f'https://{goals_host}/api/goals/staff/{login}'

    # can throw requests.Timeout exception
    response = requests.get(
        url,
        headers={tvm2.TVM_SERVICE_TICKET_HEADER: tvm_ticket},
        timeout=goals_request_timeout,
    )

    response.raise_for_status()

    return response.json()
