from django.shortcuts import render, redirect
from .models import Application, Vulnerability
from .forms import UploadFileForm
import csv
import io

def dashboard(request):
    # Placeholder data
    total_apps = Application.objects.count()
    total_vulns = Vulnerability.objects.count()
    critical_vulns = Vulnerability.objects.filter(severity='Critical').count()
    new_vulns = Vulnerability.objects.filter(status='New').count()
    applications = Application.objects.all()

    context = {
        'total_applications': total_apps,
        'total_vulnerabilities': total_vulns,
        'critical_vulnerabilities': critical_vulns,
        'new_vulnerabilities': new_vulns,
        'applications': applications,
        "project_name": "Vulnerability Scanner",
    }
    return render(request, "core/index.html", context)

def upload_inventory(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            try:
                csv_file = request.FILES['file']
                decoded_file = io.TextIOWrapper(csv_file.file, encoding='utf-8', newline='', errors='ignore')
                reader = csv.reader(decoded_file)
                # Skip header row
                next(reader)
                for row in reader:
                    if row and len(row) == 3:
                        print(f"Processing row: {row}")
                        Application.objects.create(
                            name=row[0],
                            version=row[1],
                            vendor=row[2],
                        )
                return redirect('dashboard')
            except Exception as e:
                print(f"An error occurred: {e}")
                form.add_error(None, f"An error occurred: {e}")
    else:
        form = UploadFileForm()
    return render(request, 'core/upload_inventory.html', {'form': form})
