from django.shortcuts import redirect
from django.views.generic import CreateView, DetailView
from rules.contrib.views import AutoPermissionRequiredMixin

from servala.core.models import Organization
from servala.frontend.forms import OrganizationForm
from servala.frontend.views.mixins import HtmxUpdateView, OrganizationViewMixin


class OrganizationCreateView(AutoPermissionRequiredMixin, CreateView):
    form_class = OrganizationForm
    model = Organization
    template_name = "frontend/organizations/create.html"

    def form_valid(self, form):
        instance = form.instance.create_organization(
            form.instance, owner=self.request.user
        )
        return redirect(instance.urls.base)


class OrganizationDashboardView(
    AutoPermissionRequiredMixin, OrganizationViewMixin, DetailView
):
    template_name = "frontend/organizations/dashboard.html"


class OrganizationUpdateView(OrganizationViewMixin, HtmxUpdateView):
    template_name = "frontend/organizations/update.html"
    form_class = OrganizationForm
    fragments = ("org-name", "org-name-edit")

    def get_success_url(self):
        return self.request.path
