"""
Design Overview
---------------

The core models consist of:

- ``Account`` - Such as 'Accounts Receivable', a bank account, etc. Accounts can be arranged as a tree structure,
  where the balance of the parent account is the summation of the balances of all its children.
- ``Transaction`` - Represents a movement between accounts. Each transaction must have two or more legs.
- ``Leg`` - Represents a flow of money into (debit) or out of (credit) a transaction. Debits are represented by
  negative amounts, and credits by positive amounts. The sum of all a transaction's legs must equal zero. This is
  enforced with a database constraint.

Additionally, there are models which related to the import of external bank statement data:

- ``StatementImport`` - Represents a simple import of zero or more statement lines relating to a specific ``Account``.
- ``StatementLine`` - Represents a statement line. ``StatementLine.create_transaction()`` may be called to
  create a transaction for the statement line.
"""

from django.contrib.postgres.fields.array import ArrayField
from django.contrib.postgres.fields.jsonb import JSONField
from django.db import models
from django.utils import timezone
from django.db import transaction as db_transaction
from django_smalluuid.models import SmallUUIDField, uuid_default
from djmoney.models.fields import MoneyField
from moneyed import Money

from mptt.models import MPTTModel, TreeForeignKey, TreeManager
from model_utils import Choices

from hordak import defaults
from hordak import exceptions
from hordak.defaults import MAX_DIGITS, DECIMAL_PLACES

from hordak.utilities.currency import Balance


#: Debit
DEBIT = "debit"
#: Credit
CREDIT = "credit"


def json_default():
    return {}


class AccountQuerySet(models.QuerySet):
    def net_balance(self, raw=False):
        return sum((account.balance(raw) for account in self), Balance())


class AccountManager(TreeManager):
    def get_by_natural_key(self, uuid):
        return self.get(uuid=uuid)


class Account(MPTTModel):
    """ Represents an account

    An account may have a parent, and may have zero or more children. Only root
    accounts can have a type, all child accounts are assumed to have the same
    type as their parent.

    An account's balance is calculated as the sum of all of the transaction Leg's
    referencing the account.

    Attributes:

        uuid (SmallUUID): UUID for account. Use to prevent leaking of IDs (if desired).
        name (str): Name of the account. Required.
        parent (Account|None): Parent account, nonen if root account
        code (str): Account code. Must combine with account codes of parent
            accounts to get fully qualified account code.
        type (str): Type of account as defined by :attr:`Account.TYPES`. Can only be set on
            root accounts. Child accounts are assumed to have the same time as their parent.
        TYPES (Choices): Available account types. Uses ``Choices`` from ``django-model-utils``. Types can be
            accessed in the form ``Account.TYPES.asset``, ``Account.TYPES.expense``, etc.
        is_bank_account (bool): Is this a bank account. This implies we can import bank statements into
            it and that it only supports a single currency.


    """

    TYPES = Choices(
        ("AS", "asset", "Asset"),  # Eg. Cash in bank
        ("LI", "liability", "Liability"),  # Eg. Loans, bills paid after the fact (in arrears)
        ("IN", "income", "Income"),  # Eg. Sales, housemate contributions
        ("EX", "expense", "Expense"),  # Eg. Office supplies, paying bills
        ("EQ", "equity", "Equ
ity"),  # Eg. Money from shares
        ("TR", "trading", "Currency Trading"),  # Used to represent currency conversions
    )
    uuid = SmallUUIDField(default=uuid_default(), editable=False)
    name = models.CharField(max_length=50)
    parent = TreeForeignKey(
        "self",
        null=True,
        blank=True,
        related_name="children",
        db_index=True,
        on_d
elete=models.CASCADE,
    )
    code = models.CharField(max_length=3, null=True, blank=True)
    full_code = models.CharField(max_length=100, db_index=True, unique=True, null=True, blank=True)
    # TODO: Implement this child_code_width field, as it is probably a good idea
    # child_code_width = models.PositiveSmallIntegerField(default=1)
    type = models.CharField(max_length=2, choices=TYPES, blank=True)
    is_bank_account = models.BooleanField(
        default=False,
        blank=True,
        help_text="Is this a bank account. This implies we can import bank "
        "statements into it and that it only supports a single currency",
    )
    currencies = ArrayField(models.CharField(max_length=3), db_index=True)

    objects = AccountManager.from_queryset(AccountQuerySet)()

    class MPTTMeta:
        order_insertion_by = ["code"]

    class Meta:
        unique_together = (("parent", "code"),)

    def __init__(self, *args, **kwargs):
        super(Account, self).__init__(*args, **kwargs)
        self._initial_code = self.code

    def save(self, *args, **kwargs):
        is_creating = not bool(self.pk)
        if is_creating:
            update_fields = None
        else:
            # See issues #19 & #31. It seems that on Django 1.2, django-mptt's left/right
            # tree fields get overwritten on save. The solution here is to exclude them from
            # being modified upon saving by using the save methods' update_fields argument.
            update_fields = [
                "uuid",
                "name",
                "parent",
                "code",
                "type",
                "is_bank_account",
                "currencies",
            ]
        super(Account, self).save(*args, update_fields=update_fields, **kwargs)

        do_refresh = False

        # If we've just created a non-root node then we're going to need to load
        # the type back from the DB (as it is set by trigger)
        if is_creating and not self.is_root_node():
            do_refresh = True

        # If we've just create this account or if the code has changed then we're
        # going to need to reload from the DB (full_code is set by trigger)
        if is_creating or self._initial_code != self.code:
            do_refresh = True

        if do_refresh:
            self.refresh_from_db()

    @classmethod
    def validate_accounting_equation(cls):
        """Check that all accounts sum to 0"""
        balances = [account.balance(raw=True) for account in Account.objects.root_nodes()]
        if sum(balances, Balance()) != 0:
            raise exceptions.AccountingEquationViolationError(
                "Account balances do not sum to zero. They sum to {}".format(sum(balances))
            )

    def __str__(self):
        name = self.name or "Unnamed Account"
        if self.is_leaf_node():
            try:
                balance = self.balance()
            except ValueError:
                if self.full_code:
                    return "{} {}".format(self.full_code, name)
                else:
                    return name
            else:
                if self.full_code:
                    return "{} {} [{}]".format(self.full_code, name, balance)
                else:
                    return "{} [{}]".format(name, balance)

        else:
            return name

    def natural_key(self):
        return (self.uuid,)

    @property
    def sign(self):
        """
        Returns 1 if a credit should increase the value of the
        account, or -1 if a credit should decrease the value of the
        account.

        This is based on the account type as is standard accounting practice.
        The signs can be derrived from the following expanded form of the
        accounting equation:

            Assets = Liabilities + Equity + (Income - Expenses)

        Which can be rearranged as:

            0 = Liabilities + Equity + Income - Expenses - Assets

        Further details here: https://en.wikipedia.org/wiki/Debits_and_credits

        """
        return -1 if self.type in (Account.TYPES.asset, Account.TYPES.expense) else 1

    def balance(self, as_of=None