from django.shortcuts import render, redirect
from django.contrib.admin.views.decorators import staff_member_required
from django.contrib import messages
from django.urls import reverse

from .models import GlobalSettings, AdvancedSettings
from .forms import GlobalSettingsForm, AdvancedSettingsForm
from admin_frontend.templatetags.public_urls import public_route
from admin_frontend.nav import _nav_items

@staff_member_required
@public_route(label="Settings", order=50, icon="cog")
def global_settings(request):
    settings = GlobalSettings.load()
    if request.method == "POST":
        form = GlobalSettingsForm(request.POST, instance=settings)
        if form.is_valid():
            form.save()
            messages.success(request, "Settings updated.")
            return redirect("settings:global_settings")
    else:
        form = GlobalSettingsForm(instance=settings)

    context = {"nav": _nav_items(), "form": form}
    return render(request, "admin_frontend/global_settings.html", context)

@staff_member_required
@public_route(label="Advanced Settings", order=60, icon="cog")
def advanced_settings(request):
    settings = AdvancedSettings.load()
    if request.method == "POST":
        form = AdvancedSettingsForm(request.POST, instance=settings)
        if form.is_valid():
            form.save()
            messages.success(request, "Advanced settings updated.")
            return redirect("settings:advanced_settings")
    else:
        form = AdvancedSettingsForm(instance=settings)

    context = {"nav": _nav_items(), "form": form}
    return render(request, "admin_frontend/advanced_settings.html", context)
