<?php

namespace Comitium5\DesignerBundle\UseCase\Page;

use Comitium5\DesignerBundle\Model\Interfaces\Page\DesignerPageInterface;
use Comitium5\DesignerBundle\Model\Interfaces\Page\PageFactoryInterface;
use Comitium5\DesignerBundle\Model\Interfaces\Page\PageManagerInterface;
use Comitium5\DesignerBundle\Model\Interfaces\Page\PageRepositoryInterface;

/**
 * Class CreatePageUseCase
 *
 * @author Carles Gómez <carles@bab-soft.com>
 * @package Comitium5\DesignerBundle\PageContext\Application\UseCase
 */
class CreatePageUseCase
{
    /**
     * @var PageRepositoryInterface
     */
    private $pageRepository;

    /**
     * @var PageFactoryInterface
     */
    private $pageFactory;

    /**
     * CreatePageUseCase constructor.
     *
     * @param PageRepositoryInterface $pageRepository
     * @param PageFactoryInterface $pageFactory
     */
    public function __construct(
        PageRepositoryInterface $pageRepository,
        PageFactoryInterface $pageFactory
    ) {
        $this->pageRepository = $pageRepository;
        $this->pageFactory    = $pageFactory;
    }

    /**
     * @param int $originId
     *
     * @return DesignerPageInterface|null
     */
    public function __invoke(int $originId): ?DesignerPageInterface
    {
        $page = $this
            ->pageRepository
            ->getPageFromOrigin($originId);

        if ($page instanceof DesignerPageInterface) {
            return $page;
        }

        return $this
            ->pageRepository
            ->savePage(
                $this
                    ->pageFactory
                    ->create($originId)
            );
    }
}
