# app_data - views_ipam.py
# (c) cavaliba.com

"""
IPAM views moved here from app_ipam/views.py (step 1 of deprecating
app_ipam - see app_data/ipam.py's own module docstring): the search/menu
landing page (private) and the subnet-size reference tool (calculator).
subnet_view/subnet_list/vlan_view/vlan_list were not moved - removed
outright, since ipam_subnet/ipam_vlan now have full instance_detail/
instance_list pages of their own (hierarchy/technical-info/IP-list hooks -
see app_data/hook.py). ipam_ip likewise has no dedicated view here: see
views.ipam_ip_jump() for the "click this IP" redirect.

Routed at app_data:ipam_private / app_data:ipam_calculator
(/data/private/ipam/... - app_ipam/urls.py no longer exists, the old
/ipam/private/... paths are gone; the builtin _home:ipam dashboard entry's
url field was updated to match, see app_home/migrator.py's 4.8.0 block).
app_ipam/views.py no longer exists - nothing else referenced it. Their
templates moved too: app_data/templates/app_data/ipam/private.html and
calculator.html (_paginator.html didn't move - it was only ever included
by the now-removed subnet_list/vlan_list/ip_list templates, so it was
deleted as dead code instead).

Method inventory:

Module functions:
    private, calculator
"""

from urllib.parse import urlencode

from django.shortcuts import redirect, render
from django.urls import reverse
from django.utils.translation import gettext as _

from app_data.aaa import start_view
from app_data.data import Instance
from app_data.ipam import classify_query
from app_data.schema import Schema


def _start(request, view):
    """Shared start_view() boilerplate for every IPAM view (same app/perm as today)."""
    return start_view(
        request,
        app="ipam",
        view=view,
        noauth="app_sirene:index",
        perm="p_ipam_access",
        noauthz="app_sirene:index",
    )


def private(request):
    """IPAM landing page: search box + "list of ..." buttons. Classifies the
    search box query and redirects to the matching generic app_data view -
    ipam_subnet/ipam_ip's own instance_detail if an exact keyname match
    exists (ipam_subnet's keyname is the CIDR itself, ipam_ip's own jump
    view handles its hexip keyname), else that classname's instance_list
    prefiltered by the query."""

    context = _start(request, "private")
    if context["redirect"]:
        return redirect(context["redirect"])

    context["count_ip"] = Schema.count_instances("ipam_ip")
    context["count_subnet"] = Schema.count_instances("ipam_subnet")
    context["count_vlan"] = Schema.count_instances("ipam_vlan")

    query = request.GET.get("query", "").strip()
    if not query:
        return render(request, "app_data/ipam/private.html", context)

    kind, value = classify_query(query)

    if kind == "ip":
        return redirect(f"{reverse('app_data:ipam_ip_jump')}?{urlencode({'ip': value})}")

    if kind == "subnet":
        subnet_instance = Instance.from_keyname(classname="ipam_subnet", keyname=value)
        if subnet_instance:
            return redirect("app_data:instance_detail", id=subnet_instance.id)
        return redirect(
            f"{reverse('app_data:instance_list', kwargs={'classname': 'ipam_subnet'})}"
            f"?{urlencode({'query': value})}"
        )

    if kind == "text":
        return redirect(
            f"{reverse('app_data:instance_list', kwargs={'classname': 'ipam_vlan'})}"
            f"?{urlencode({'query': value})}"
        )

    # ipv6_unsupported or empty: stay on the landing page with a message, no redirect loop
    context["query"] = query
    if kind == "ipv6_unsupported":
        context["error"] = _("IPv6 is not supported - this is an IPv4-only view.")
    return render(request, "app_data/ipam/private.html", context)


def calculator(request):
    """IPv4 subnet size reference tool - static content, no query params."""

    context = _start(request, "calculator")
    if context["redirect"]:
        return redirect(context["redirect"])

    return render(request, "app_data/ipam/calculator.html", context)
