<?php

declare(strict_types=1);

namespace App\Service;

use App\Entity\Awardee;
use Doctrine\ORM\EntityManager;
use UtilityModule\Hydrator\DoctrineObject;

class AwardeeManager
{
    /** @var EntityManager */
    private $entityManager;

    /** @var DoctrineObject */
    private $hydrator;

    public function __construct(
        EntityManager $entityManager,
        DoctrineObject $hydrator
    ) {
        $this->entityManager = $entityManager;
        $this->hydrator = $hydrator;
    }

    public function getAwardees(): ?array
    {
        return $this->entityManager->getRepository(Awardee::class)->findBy([], [
            'year' => 'DESC',
        ]);
    }

    /**
     * @param int $year
     * @return Awardee[]
     */
    public function getAwardeesByYear(int $year): ?array
    {
        return $this->entityManager->getRepository(Awardee::class)->findBy([
            'year' => $year,
        ]);
    }

    public function getAwardee(int $id): ?Awardee
    {
        /** @var Awardee $awardee */
        $awardee = $this->entityManager->getRepository(Awardee::class)->find($id);
        return $awardee;
    }

    /**
     * @param string $slug
     * @return Awardee|null
     */
    public function getAwardeeFromSlug(string $slug): ?Awardee
    {
        /** @var Awardee $awardee */
        $awardee = $this->entityManager->getRepository(Awardee::class)->findOneBy([
           'slug' => $slug,
        ]);
        return $awardee;
    }

    /**
     * @return Awardee
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function create($data): Awardee
    {
        /** @var Awardee $awardee */
        $awardee = $this->hydrator->hydrate($data, new Awardee());
        $this->entityManager->persist($awardee);
        $this->entityManager->flush();
        return $awardee;
    }

    /**
     * @param int $id
     * @param $data
     * @return Awardee
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function update(int $id, $data): Awardee
    {
        $awardee = $this->entityManager->getRepository(Awardee::class)->find($id);
        /** @var Awardee $awardee */
        $awardee = $this->hydrator->hydrate($data, $awardee);
        $this->entityManager->persist($awardee);
        $this->entityManager->flush();
        return $awardee;
    }

    /**
     * @param int $id
     * @return bool
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function delete(int $id): bool {
        if (null !== ($entity = $this->getAwardee($id))) {
            $this->entityManager->remove($entity);
            $this->entityManager->flush();
            return true;
        }
        return false;
    }
}
