<?php

namespace App\Entity\EntityTrait;

use App\Enum\CurrencyEnum;
use App\Flux\AccountInterface;

trait HasAccountsTrait
{
    /**
     * Get accounts.
     *
     * @return AccountGroupe[]|ArrayCollection
     */
    public function getAccounts()
    {
        return $this->accounts;
    }

    /**
     * Set accounts.
     *
     * @return $this
     */
    public function setAccounts($accounts)
    {
        $this->accounts = $accounts;

        return $this;
    }

    public function hasAccountWithCurrency(string $currency): ?AccountInterface
    {
        if (null != $this->getAccountWithCurrency($currency)) {
            return true;
        }

        return false;
    }

    public function getAccountWithCurrency(string $currency): ?AccountInterface
    {
        if (!in_array($currency, CurrencyEnum::getAvailableTypes())) {
            throw new \Exception('Opération impossible ! Type de currency  ' . $currency . ' inexistant');
        }
        foreach ($this->accounts as $account) {
            if ($account->getCurrency() == $currency) {
                return $account;
            }
        }

        // @TODO change getAccountWithCurrency with hasAccountWithCurrency when creating account and throw exception elsewhere !
        // throw new \Exception('Compte introuvable : currency : ' . $currency . ', objet : ' . $this->__toString());
        return null;
    }

    /**
     * @param AccountInterface $account
     *
     * @return $this
     */
    public function addAccount(AccountInterface $account)
    {
        if (!$this->accounts->contains($account)) {
            $this->accounts[] = $account;
            $account->setAccountableObject($this);
        }

        return $this;
    }

    /**
     * @param AccountInterface $account
     *
     * @return $this
     */
    public function removeAccount(AccountInterface $account)
    {
        if ($this->accounts->contains($account)) {
            $this->accounts->removeElement($account);
            $account->setAccountableObject(null);
        }

        return $this;
    }

    public function getEmlcAccount(): ?AccountInterface
    {
        return $this->getAccountWithCurrency(CurrencyEnum::CURRENCY_EMLC);
    }

    public function getMlcAccount(): ?AccountInterface
    {
        return $this->getAccountWithCurrency(CurrencyEnum::CURRENCY_MLC);
    }

    public function getEuroAccount(): ?AccountInterface
    {
        return $this->getAccountWithCurrency(CurrencyEnum::CURRENCY_EURO);
    }

    public function getMlcNantieAccount(): ?AccountInterface
    {
        return $this->getAccountWithCurrency(CurrencyEnum::CURRENCY_MLC_NANTIE);
    }
}
