"""
This module defines views for website handling.

"""
from __future__ import absolute_import

from django.contrib import messages
from django.shortcuts import get_object_or_404, redirect
from django.utils.translation import gettext as _
from django.views.generic.edit import CreateView, DeleteView
from gvacommon.viewmixins import StaffOrSelfLoginRequiredMixin

from domains.models import HostingDomain
from gvawebcore.views import HostingPackageAndCustomerMixin

from .forms import AddWebsiteForm
from .models import Website


class AddWebsite(
    HostingPackageAndCustomerMixin, StaffOrSelfLoginRequiredMixin, CreateView
):
    """
    This view is used to setup new websites for a customer hosting package.

    """

    model = Website
    context_object_name = "website"
    template_name_suffix = "_create"
    form_class = AddWebsiteForm

    def get_form_kwargs(self):
        kwargs = super(AddWebsite, self).get_form_kwargs()
        kwargs.update(
            {
                "hostingpackage": self.get_hosting_package(),
                "domain": get_object_or_404(
                    HostingDomain, domain=self.kwargs["domain"]
                ),
            }
        )
        return kwargs

    def get_context_data(self, **kwargs):
        context = super(AddWebsite, self).get_context_data(**kwargs)
        context.update(
            {
                "customer": self.get_customer_object(),
                "domain": get_object_or_404(
                    HostingDomain, domain=self.kwargs["domain"]
                ),
            }
        )
        return context

    def form_valid(self, form):
        website = form.save()
        messages.success(
            self.request,
            _("Successfully added website {subdomain}.{domain}").format(
                subdomain=website.subdomain, domain=website.domain.domain
            ),
        )
        return redirect(self.get_hosting_package())


class DeleteWebsite(
    HostingPackageAndCustomerMixin, StaffOrSelfLoginRequiredMixin, DeleteView
):
    """
    This view is used to delete websites in a customer hosting package.

    """

    context_object_name = "website"
    model = Website

    def get_context_data(self, **kwargs):
        context = super(DeleteWebsite, self).get_context_data(**kwargs)
        context.update(
            {
                "customer": self.get_customer_object(),
                "hostingpackage": self.get_hosting_package(),
            }
        )
        return context

    def get_success_url(self):
        return self.get_hosting_package().get_absolute_url()
