from django.shortcuts import render
from .models import VulnerabilityDB
from django.contrib.auth.decorators import login_required
from .forms import VulnerabilityDBForm
from django.http import HttpResponseRedirect
from django.http import HttpResponse

# Create your views here.
from django.http import JsonResponse




@login_required
def vulerabilitiydb(request):

    vulnerability = VulnerabilityDB.objects.all()
    return render(request, "Vulnerability-Database/vulerabilitiydb.html", {'vulnerability': vulnerability})
    

@login_required
def vulerabilitiydbadd(request):
    form = VulnerabilityDBForm()
    if request.method == 'POST':
        form = VulnerabilityDBForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponse(status=200)
            
        else:
            return HttpResponse(status=500)
            print(form.errors )
            print(form.non_field_errors )
       

    if request.method == 'GET':
        context = {'form':form}
        return render(request, "Vulnerability-Database/vulerabilitiydbadd.html", context)

   
@login_required
def vulerabilitiydbedit(request, pk):
    vlun = VulnerabilityDB.objects.get(id=pk)
    form = VulnerabilityDBForm(instance=vlun)
    
    if request.method == 'POST':
        form = VulnerabilityDBForm(request.POST, instance=vlun)
        if form.is_valid():
            form.save()
            responseData = {'Status':'Success'}
            return JsonResponse(responseData)
        else:
            responseData = {'Status':'Fail'}
            return JsonResponse(responseData)
            
    context = {'form':form}
    return render(request, 'Vulnerability-Database/vulerabilitiydbedit.html', context)
    
@login_required
def vulerabilitiydbdelete(request, pk):
    VulnerabilityDB.objects.get(pk=pk).delete()
    return HttpResponse(status=200)