from uuid import uuid4

from django.apps import apps
from django.db import models
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from main.models import NummiModel


class Account(NummiModel):
    id = models.UUIDField(primary_key=True, default=uuid4, editable=False)
    name = models.CharField(max_length=64, default=_("Account"), verbose_name=_("Name"))
    icon = models.SlugField(
        max_length=24,
        default="bank",
        verbose_name=_("Icon"),
    )
    default = models.BooleanField(default=False, verbose_name=_("Default"))
    archived = models.BooleanField(default=False, verbose_name=_("Archived"))

    def save(self, *args, **kwargs):
        if self.default:
            for ac in Account.objects.filter(user=self.user, default=True):
                ac.default = False
                ac.save()
        super().save(*args, **kwargs)

    def __str__(self):
        return str(self.name)

    def get_absolute_url(self):
        return reverse("account", args=(self.pk,))

    def get_delete_url(self):
        return reverse("del_account", args=(self.pk,))

    @property
    def transactions(self):
        return apps.get_model("transaction", "Transaction").objects.filter(
            statement__account=self
        )

    class Meta:
        ordering = ["-default", "archived", "name"]
        verbose_name = _("Account")
        verbose_name_plural = _("Accounts")


class AccountModel(NummiModel):
    account = models.ForeignKey(
        Account,
        on_delete=models.CASCADE,
        verbose_name=_("Account"),
    )

    class Meta:
        abstract = True
