# app_ipam - views.py
# (c) cavaliba.com


from django.shortcuts import redirect, render

from app_data.aaa import start_view
from app_data.schema import Schema
from app_ipam.common import IpamIP, IpamSubnet, is_ipv4, is_ipv4_subnet


#  -----------------------------------------------------------------------------------------
def private(request):

    context = start_view(
        request,
        app="ipam",
        view="private",
        noauth="app_sirene:index",
        perm="p_ipam_access",
        noauthz="app_sirene:index",
    )
    if context["redirect"]:
        return redirect(context["redirect"])
    # aaa = context["aaa"]

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

    query = request.GET.get("query", None)
    if not query or len(query) == 0:
        return render(request, "app_ipam/private.html", context)

    #  TODO: sanitize

    query = query.strip()

    context["query"] = query

    # # IP ?
    # is_ip = False
    # try:
    #     ipobj = ipaddress.ip_address(query)
    #     is_ip = True
    # except Exception:
    #     pass

    # is_subnet = False
    # try:
    #     ipobj = ipaddress.ip_network(query)
    #     is_subnet = True
    # except Exception:
    #     pass

    if is_ipv4(query):
        ipobj = IpamIP(query, set_subnet=True)
        if ipobj:
            context["ip"] = ipobj
            context["subnet"] = ipobj.subnet
            context["parent"] = ipobj.parent_subnet
            context["child"] = ipobj.child_subnet
            context["related"] = ipobj.get_related_objects()

    elif is_ipv4_subnet(query):
        subobj = IpamSubnet(query, set_subnet=True)
        if subobj:
            context["subnet"] = subobj
            context["parent"] = subobj.parent_subnet
            context["child"] = subobj.child_subnet

    # TODO: full text VLAN query
    else:
        pass

    return render(request, "app_ipam/private.html", context)


#  -----------------------------------------------------------------------------------------
def calculator(request):

    context = start_view(
        request,
        app="ipam",
        view="calculator",
        noauth="app_sirene:index",
        perm="p_ipam_access",
        noauthz="app_sirene:index",
    )
    if context["redirect"]:
        return redirect(context["redirect"])
    # aaa = context["aaa"]

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