<?php

namespace App\Repository;

use App\Entity\Adherent;
use App\Entity\Comptoir;
use App\Entity\Groupe;
use App\Entity\Operation;
use App\Entity\OperationAdherent;
use App\Entity\OperationComptoir;
use App\Entity\OperationGroupe;
use App\Entity\OperationPrestataire;
use App\Entity\OperationSiege;
use App\Entity\Prestataire;
use App\Entity\Siege;
use App\Enum\CurrencyEnum;
use App\Flux\AccountableInterface;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

/**
 * @method Operation|null find($id, $lockMode = null, $lockVersion = null)
 * @method Operation|null findOneBy(array $criteria, array $orderBy = null)
 * @method Operation[]    findAll()
 * @method Operation[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 */
class OperationRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, Operation::class);
    }

    /**
     * @return Account[] Returns an array of Account objects
     */
    public function findByAccountable(AccountableInterface $object, string $currency = null)
    {
        $query = null;
        if ($object instanceof Prestataire) {
            $query = $this->getEntityManager()->getRepository(OperationPrestataire::class)->findBy(['account' => $object->getEmlcAccount()], ['createdAt' => 'DESC']);
        } elseif ($object instanceof Adherent) {
            $query = $this->getEntityManager()->getRepository(OperationAdherent::class)->findBy(['account' => $object->getEmlcAccount()], ['createdAt' => 'DESC']);
        } elseif ($object instanceof Groupe) {
            $query = $this->getEntityManager()->getRepository(OperationGroupe::class)->findBy(['account' => $object->getMlcAccount()], ['createdAt' => 'DESC']);
        } elseif ($object instanceof Comptoir) {
            $query = $this->getEntityManager()->getRepository(OperationComptoir::class)->findBy(['account' => $object->getMlcAccount()]);
        } elseif ($object instanceof Siege) {
            if (null != $currency) {
                if (!in_array($currency, CurrencyEnum::getAvailableTypes())) {
                    throw new \Exception('Opération impossible ! Type de currency  ' . $currency . ' inexistant');
                }
                $siege = $this->getEntityManager()->getRepository(Siege::class)->getTheOne();
                $query = $this->getEntityManager()->getRepository(OperationSiege::class)->findBy(['account' => $object->getAccountWithCurrency($currency)], ['createdAt' => 'DESC']);
            } else {
                $query = $this->em->getRepository(OperationSiege::class)->findBy(['account' => $object->getMlcAccount()], ['createdAt' => 'DESC']);
            }
        }
        if (null == $query) {
            return null;
        }

        return $query
            ->getQuery()
        ;
    }
}
