from django.core.exceptions import ValidationError

from .models import WorkSpecification, DataProductFilter, Group

from django.forms import ModelForm, CharField, ChoiceField, ModelChoiceField


class WorkSpecificationForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['predecessor_specification'].required = False
        self.fields['filters'].required = False
        self.fields['group'].required = False

    def _extract_filters(self):
        filter_names = [filter_name[0] for filter_name in DataProductFilter.objects.all().values_list('field')]
        filters = {}
        for filter_name in filter_names:
            if filter_name in self.data and self.data[filter_name] != "":
                filters[filter_name] = self.data[filter_name]
        return filters

    def clean(self):
        self.cleaned_data = super().clean()
        self.cleaned_data["filters"] = self._extract_filters()
        if not 'obs_id' in self.cleaned_data["filters"]:
            raise ValidationError(["SAS ID: This field is required."])

        return self.cleaned_data

    class Meta:
        model = WorkSpecification
        fields = ['filters', 'selected_workflow', 'selected_workflow_tag', 'processing_site',
                  'predecessor_specification', 'batch_size', 'group', 'is_auto_submit']
        labels = {
            'selected_workflow': 'Selected workflow',
            'selected_workflow_tag': 'Workflow tag',
            'processing_site': 'Processing Site (ATDB)',
            'predecessor_specification': 'Predecessor',
            'batch_size': 'Files per task',
            'group': 'Group',
            'is_auto_submit': 'Auto submit'
        }
        help_texts = {'selected_workflow': "The pipeline to run on the processing site.",
                      'selected_workflow_tag': "The pipeline's tag as specified in ATDB.",
                      'processing_site': "The ATDB processing site to run a specific workflow in.",
                      'predecessor_specification': "The related predecessor of the current work specification.",
                      'batch_size': "The number of files every task generated by this work specification should have. Example: 10 files in total can be split into 5 tasks of 2 files.",
                      'group': "Include the work specification to a group. Note that it will inherit the group's processing site and workflow specifications.",
                      'is_auto_submit': "By checking this box, the work specification will be directly sent to the processing site and thus does not need inspection."
                      }


class GroupForm(ModelForm):
    obs_ids = CharField(label='SAS IDs',
                        help_text="A list of SAS IDs separated with a comma. Example: 123, 456, 789",
                        required=True)

    class Meta:
        model = Group
        fields = ['name', 'selected_workflow', 'selected_workflow_tag', 'processing_site', 'obs_ids']
        labels = {
            'selected_workflow': 'Selected workflow',
            'selected_workflow_tag': 'Workflow tag',
            'processing_site': 'Processing Site (ATDB)',
            'name': 'Name',
        }
        help_texts = {'selected_workflow': "The pipeline to run on the processing site.",
                      'selected_workflow_tag': "The pipeline's tag as specified in ATDB.",
                      'processing_site': "The ATDB processing site to run a specific workflow in.",
                      'name': "A unique and custom name for this group"
                      }