<?php

namespace Comitium5\DesignerBundle\Repository\Page;

use Comitium5\DesignerBundle\Model\Interfaces\Page\DesignerPageInterface;
use Comitium5\DesignerBundle\Model\Interfaces\Page\PageRepositoryInterface;
use Comitium5\DesignerBundle\Model\Interfaces\Template\TemplateInterface;
use Comitium5\DesignerBundle\Repository\AbstractRepository;
use Doctrine\Common\Collections\ArrayCollection;
use phpDocumentor\Reflection\Types\Array_;

/**
 * Class PageDoctrineRepository
 *
 * @author Carles Gómez <carles@bab-soft.com>
 * @package Comitium5\DesignerBundle\PageContext\Infrastructure\Repository
 */
class PageDoctrineRepository extends AbstractRepository implements PageRepositoryInterface
{
    /**
     * @param int $pageId
     *
     * @return DesignerPageInterface|null
     */
    public function getPage(int $pageId): ?DesignerPageInterface
    {
        return $this->find($pageId);
    }

    /**
     * @param int $originId
     *
     * @return DesignerPageInterface|null
     */
    public function getPageFromOrigin(int $originId): ?DesignerPageInterface
    {
        return $this->findOneBy([
            'originId' => $originId
        ]);
    }

    /**
     * @param DesignerPageInterface $page
     *
     * @return DesignerPageInterface
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function savePage(DesignerPageInterface $page): DesignerPageInterface
    {
        $this
            ->_em
            ->persist($page);

        $this
            ->_em
            ->flush($page);

        return $page;
    }

    /**
     * @param DesignerPageInterface $page
     *
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function removePage(DesignerPageInterface $page): void
    {
        $this
            ->_em
            ->remove($page);

        $this
            ->_em
            ->flush();
    }

    /**
     * @param TemplateInterface $template
     *
     * @return array|null
     */
    public function findByTemplate(TemplateInterface $template) : ?array
    {
        return $this
            ->_em
            ->createQueryBuilder()
            ->select("p")
            ->from("Comitium5DesignerBundle:Page", "p")
            ->where("p.template = :templateId")
            ->setParameter("templateId", $template->getId())
            ->getQuery()
            ->getResult();
    }
}
