"""Views."""

from esi.decorators import token_required

from django.contrib.auth.decorators import login_required, permission_required
from django.shortcuts import render

from allianceauth.services.hooks import get_extension_logger

from . import esi as pootest_esi

logger = get_extension_logger(__name__)

# ESI scopes required to read a corporation's structures. The authenticating
# character must additionally hold the Director or Station Manager role.
STRUCTURE_SCOPES = [
    "esi-corporations.read_structures.v1",
    "esi-universe.read_structures.v1",
]


@login_required
@permission_required("pootest.basic_access")
def index(request):
    """Render index view."""
    context = {
        "text": "Hello, World! This is aa-pootest.",
        "page_title": "Welcome",
    }
    return render(request, "pootest/index.html", context)


@login_required
@permission_required("pootest.basic_access")
@token_required(scopes=STRUCTURE_SCOPES)
def structures(request, token):
    """List the structures owned by the corporation of the authenticated
    character, one per line.

    The character must be a Director or Station Manager of the corporation,
    otherwise ESI returns no data / a 403.
    """
    structure_names = []
    error = None
    try:
        corporation_id = pootest_esi.get_corporation_id_for_character(
            token.character_id
        )
        structure_names = pootest_esi.fetch_corporation_structures(
            corporation_id, token
        )
    except Exception as exc:  # noqa: BLE001 - surface any ESI failure to the user
        logger.warning("Could not load corporation structures: %s", exc)
        error = (
            "Could not read structures from ESI. The selected character must be "
            "a Director or Station Manager in the corporation, and must have "
            "granted the required ESI scopes."
        )

    context = {
        "page_title": "Corporation Structures",
        "structures": structure_names,
        "structure_count": len(structure_names),
        "error": error,
    }
    return render(request, "pootest/structures.html", context)
