"""This module holds the forms for the ``trainings`` app."""

from django import forms

import waffle

from mtp.apps.accounts.constants import GROUPTYPE_BUSINESS_UNIT
from mtp.apps.accounts.forms import MTPUserSelectMultipleWidget
from mtp.apps.accounts.models import Group, MTPUser

from .models import Training, TrainingSession


def _toggle_locks(fields):
    """
    Remove ``*_lock`` fields from the ``TrainingForm`` according to the
    ``enable_training_locks`` Waffle switch.

    """
    if not waffle.switch_is_active('enable_training_locks'):
        lock_fields = [field for field in fields if field.endswith('_lock')]
        for lock_field in lock_fields:
            del fields[lock_field]


class TrainingForm(forms.ModelForm):
    """Form for ``mtp.apps.trainings.models.Training`` model."""

    class Meta:
        model = Training
        fields = [
            'name',
            'description',
            'theme',
            'job_profile',
            'business_unit',
            'thumbnail_image',
            'header_image',
        ]

    def __init__(self, *args, **kwargs):
        """Init the form accordingly to the provided kwargs

        Parameters
        ----------
        **kwargs
            - current_user: ``mtp.apps.accounts.models.MTPUser`` instance
                Used to filter the available groups for the business_unit field.

        """

        current_user = kwargs.pop('current_user')

        super().__init__(*args, **kwargs)

        # Make sure there's no empty choice in the theme selector.
        if 'theme' in self.fields:
            self.fields['theme'].empty_label = None

        # Filter the job_profile which can be added
        self.fields['job_profile'].queryset = Group.objects.job_profiles().non_deleted().filter(
            member_roles__user=current_user
        )

        # Filter the groups that can be added,
        # accordingly to the user's managed groups
        self.fields['business_unit'].queryset = Group.objects.filter(
            member_roles__user=current_user,
            type__name=GROUPTYPE_BUSINESS_UNIT
        )


class TrainingSessionForm(forms.ModelForm):
    """Form for ``mtp.apps.trainings.models.TrainingSession`` model."""

    users = forms.ModelMultipleChoiceField(
        widget=MTPUserSelectMultipleWidget(
            attrs={'data-allow-clear': 'false'}
        ),
        required=False,
        queryset=MTPUser.objects.non_deleted().active().trainees(),
    )

    class Meta:
        model = TrainingSession
        fields = (
            'training',
            'trainer',
            'users',
            'start_date',
            'end_date',
            'state',
            'permissions',
        )

    def __init__(self, *args, **kwargs):
        """Init the form accordingly to the provided kwargs

        Parameters
        ----------
        **kwargs
            - remove_training_field: bool
                If ``True``, the training field is removed.
            - remove_trainer_field: bool
                If ``True``, the trainer field is removed.
            - current_user: ``mtp.apps.accounts.models.MTPUser`` instance
                Used to filter the trainings which can be used in the
                training field.

        """

        remove_training_field = kwargs.pop('remove_training_field')
        remove_trainer_field = kwargs.pop('remove_trainer_field')
        current_user = kwargs.pop('current_user')

        super().__init__(*args, **kwargs)

        if remove_training_field:
            self.fields.pop('training')
        else:
            self.fields['training'].queryset = Training.objects.available_for_user(
                current_user
            )

        if remove_trainer_field:
            self.fields.pop('trainer')
        else:
            self.fields['trainer'].queryset = MTPUser.objects.non_deleted().active().trainers()
