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



from django.shortcuts import render, redirect



from app_user.aaa import start_view

from app_data.data import count_instance


from app_ipam.common import IpamIP
from app_ipam.common import IpamSubnet
from app_ipam.common import is_ipv4
from app_ipam.common import 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"] = count_instance("ipam_subnet")
    context["count_vlan"] = count_instance("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:
    #     pass

    # is_subnet = False
    # try:
    #     ipobj = ipaddress.ip_network(query)
    #     is_subnet = True
    # except:
    #     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)
