import json

from account.forms import AccountSelect
from django import forms
from django.forms.widgets import Select
from django.utils.translation import gettext_lazy as _
from main.forms import NummiFileInput, NummiForm
from transaction.models import Transaction

from .models import Statement


class StatementForm(NummiForm):
    class Meta:
        model = Statement
        fields = ["account", "start_date", "date", "start_value", "value", "file"]
        widgets = {
            "file": NummiFileInput,
            "account": AccountSelect,
        }

    meta_fieldsets = [
        [
            ["account"],
            ["start_date", "start_value"],
            ["date", "value"],
            ["file"],
        ],
    ]

    def __init__(self, *args, **kwargs):
        _user = kwargs.pop("user")
        _disable_account = kwargs.pop("disable_account", False)
        super().__init__(*args, **kwargs)
        self.fields["account"].queryset = _user.account_set.exclude(archived=True)
        self.fields["transactions"] = forms.MultipleChoiceField(
            choices=(
                ((_transaction.id), _transaction)
                for _transaction in Transaction.objects.filter(
                    user=_user, statement=None
                )
            ),
            label=_("Add transactions"),
            required=False,
        )

        self.fields["account"].widget.attrs |= {
            "class": "account",
            "data-icons": json.dumps(
                {
                    str(acc.id): acc.icon
                    for acc in self.fields["account"].queryset.only("id", "icon")
                }
            ),
        }

        if _disable_account:
            self.fields["account"].disabled = True

    def save(self, *args, **kwargs):
        instance = super().save(*args, **kwargs)
        new_transactions = Transaction.objects.filter(
            id__in=self.cleaned_data["transactions"]
        )

        instance.transaction_set.add(*new_transactions, bulk=False)
        return instance


class StatementSelect(Select):
    template_name = "statement/forms/widgets/statement.html"
