from django.shortcuts import render, redirect, get_object_or_404
from .models import Unit
from .forms import UnitForm
import subprocess
import os
import signal

SIMULATION_PID_FILE = 'simulation.pid'

def dashboard(request):
    return render(request, 'core/dashboard.html', {'project_name': 'Project Lifeline'})

def simulation_control(request):
    pid = None
    if os.path.exists(SIMULATION_PID_FILE):
        with open(SIMULATION_PID_FILE, 'r') as f:
            try:
                pid = int(f.read().strip())
                # Check if the process is still running
                os.kill(pid, 0)
            except (ValueError, OSError):
                pid = None
                if os.path.exists(SIMULATION_PID_FILE):
                    os.remove(SIMULATION_PID_FILE)


    if request.method == 'POST':
        if 'start' in request.POST and not pid:
            # Start the simulation
            process = subprocess.Popen(['python3', 'manage.py', 'run_simulation'])
            with open(SIMULATION_PID_FILE, 'w') as f:
                f.write(str(process.pid))
            pid = process.pid
            return redirect('simulation_control')
        elif 'stop' in request.POST and pid:
            # Stop the simulation
            try:
                os.kill(pid, signal.SIGTERM)
                if os.path.exists(SIMULATION_PID_FILE):
                    os.remove(SIMULATION_PID_FILE)
                pid = None
            except OSError:
                # Process might have already died
                if os.path.exists(SIMULATION_PID_FILE):
                    os.remove(SIMULATION_PID_FILE)
                pid = None
            return redirect('simulation_control')

    return render(request, 'core/simulation_control.html', {'simulation_running': pid is not None, 'project_name': 'Project Lifeline'})


def unit_list(request):
    units = Unit.objects.all()
    return render(request, 'core/unit_list.html', {'units': units, 'project_name': 'Project Lifeline'})

def unit_update(request, pk):
    unit = get_object_or_404(Unit, pk=pk)
    if request.method == 'POST':
        form = UnitForm(request.POST, instance=unit)
        if form.is_valid():
            form.save()
            return redirect('unit_list')
    else:
        form = UnitForm(instance=unit)
    return render(request, 'core/unit_form.html', {'form': form, 'unit': unit, 'project_name': 'Project Lifeline'})
