from django import forms
from django.utils.translation import gettext_lazy as _

from .models import AccessRight, ApiUser, AvailabilityParameters


class ApiUserForm(forms.ModelForm):
    class Meta:
        model = ApiUser
        exclude = []


class AccessRightForm(forms.ModelForm):
    confirm_open_access = forms.BooleanField(
        label=_('Allow open access'), required=False, widget=forms.HiddenInput()
    )

    class Meta:
        model = AccessRight
        exclude = []
        widgets = {
            'codename': forms.HiddenInput(),
            'resource_type': forms.HiddenInput(),
            'resource_pk': forms.HiddenInput(),
        }

    def add_confirmation_checkbox(self):
        self.add_error(None, _('Selected user has no security.'))
        self.add_error(
            'confirm_open_access',
            _(
                'Check this box if you are sure you want to allow unauthenticated access to '
                'endpoints. Otherwise, select a different API User.'
            ),
        )
        self.fields['confirm_open_access'].widget = forms.CheckboxInput()

    @property
    def allow_open_access(self):
        return self.cleaned_data['confirm_open_access']


class AvailabilityParametersForm(forms.ModelForm):
    class Meta:
        model = AvailabilityParameters
        fields = ['run_check', 'notification_delays']
        widgets = {
            'notification_delays': forms.TextInput,
        }


class ImportSiteForm(forms.Form):
    site_json = forms.FileField(label=_('Site Export File'))
    import_users = forms.BooleanField(label=_('Import users and access rights'), required=False)


class BaseQueryFormMixin:
    def clean_slug(self):
        slug = self.cleaned_data['slug']

        queryset = self.instance.resource.queries.filter(slug=slug)
        if self.instance.pk:
            queryset = queryset.exclude(pk=self.instance.pk)
        if queryset.exists():
            raise forms.ValidationError(_('A query with this slug already exists'))

        return slug

    def clean_name(self):
        name = self.cleaned_data['name']

        queryset = self.instance.resource.queries.filter(name=name)
        if self.instance.pk:
            queryset = queryset.exclude(pk=self.instance.pk)
        if queryset.exists():
            raise forms.ValidationError(_('A query with this name already exists'))

        return name
