from django import forms

class ImportForm(forms.Form):
    file = forms.FileField(allow_empty_file=False)
    dry_run = forms.BooleanField(initial=True, required=False, help_text="Preview changes without saving")


class EntryForm(forms.Form):
    subject = forms.CharField(required=False)
    illustration = forms.CharField(required=False, widget=forms.Textarea)
    application = forms.CharField(required=False, widget=forms.Textarea)
    scripture_raw = forms.CharField(required=False)
    source = forms.CharField(required=False)
    talk_title = forms.CharField(required=False)

    # Coerce blank -> None, digits -> int
    talk_number = forms.TypedChoiceField(
        required=False,
        choices=[("", "—")] + [(str(i), str(i)) for i in range(1, 201)],  # blank + 1-200
        coerce=lambda v: int(v) if str(v).isdigit() else None,
        empty_value=None,  # when the blank option is chosen, cleaned_data["talk_number"] == None
    )

    entry_code = forms.CharField(required=False)
    date_added = forms.DateField(required=False, widget=forms.DateInput(attrs={"type": "date"}))
    date_edited = forms.DateField(required=False, widget=forms.DateInput(attrs={"type": "date"}))

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        big_inputs = ("subject", "scripture_raw", "source", "talk_title", "entry_code")
        textareas  = ("illustration", "application")

        for name in big_inputs:
            if name in self.fields:
                self.fields[name].widget.attrs.update({
                    "class": "search-input input-hero"
                })

        for name in textareas:
            if name in self.fields:
                self.fields[name].widget.attrs.update({
                    "class": "search-input input-hero textarea-hero"
                })

        if "talk_number" in self.fields:
            self.fields["talk_number"].widget.attrs.update({
                "class": "search-input input-hero"
            })

        if "date_added" in self.fields:
            self.fields["date_added"].widget.attrs.update({"class": "search-input input-hero"})
        if "date_edited" in self.fields:
            self.fields["date_edited"].widget.attrs.update({"class": "search-input input-hero"})

    # (Optional) keep it bullet-proof even if the choices/widget change someday
    def clean_talk_number(self):
        v = self.cleaned_data.get("talk_number")
        return v if isinstance(v, int) else None