"""
This module defines form classes for user database editing.

"""
from __future__ import absolute_import

from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from django import forms
from django.urls import reverse
from django.utils.translation import gettext_lazy as _

from gvawebcore.forms import PasswordModelFormMixin

from .models import DB_TYPES, DatabaseUser, UserDatabase


class AddUserDatabaseForm(forms.ModelForm, PasswordModelFormMixin):
    """
    This form is used to create new user database instances.

    """

    db_type = forms.TypedChoiceField(
        label=_("Database type"),
        choices=DB_TYPES,
        widget=forms.RadioSelect,
        coerce=int,
    )

    class Meta:
        model = UserDatabase
        fields = []

    def __init__(self, *args, **kwargs):
        self.hosting_package = kwargs.pop("hostingpackage")
        self.available_dbtypes = kwargs.pop("dbtypes")
        super(AddUserDatabaseForm, self).__init__(*args, **kwargs)
        self.fields["db_type"].choices = self.available_dbtypes
        if len(self.available_dbtypes) == 1:
            self.fields["db_type"].initial = self.available_dbtypes[0][0]
            self.fields["db_type"].widget = forms.HiddenInput()
        self.helper = FormHelper()
        self.helper.form_action = reverse(
            "add_userdatabase", kwargs={"package": self.hosting_package.id}
        )
        self.helper.add_input(Submit("submit", _("Create database")))

    def save(self, commit=True):
        """
        Setup a new database with a new database user with the specified
        password.

        :param boolean commit: whether to save the created database
        :return: database instance
        :rtype: :py:class:`userdbs.models.UserDatabase`

        """
        data = self.cleaned_data
        self.instance = UserDatabase.objects.create_userdatabase_with_user(
            data["db_type"],
            self.hosting_package.osuser,
            password=data["password1"],
            commit=commit,
        )
        return super(AddUserDatabaseForm, self).save(commit)


class ChangeDatabaseUserPasswordForm(forms.ModelForm, PasswordModelFormMixin):
    """
    This form is used to change the password of a database user.

    """

    class Meta:
        model = DatabaseUser
        fields = []

    def __init__(self, *args, **kwargs):
        self.hosting_package = kwargs.pop("hostingpackage")
        super(ChangeDatabaseUserPasswordForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_action = reverse(
            "change_dbuser_password",
            kwargs={
                "slug": self.instance.name,
                "package": self.hosting_package.id,
            },
        )
        self.helper.add_input(Submit("submit", _("Set password")))

    def save(self, commit=True):
        self.instance.set_password(self.cleaned_data["password1"])
        return super(ChangeDatabaseUserPasswordForm, self).save()
