<?php


namespace Diamond\Factory;


use Core\Exceptions\IsRedirectResponseException;
use Core\Exceptions\PageNotFound;
use Core\Exceptions\ResponseException;
use Diamond\Application\Content\ContentService;
use Diamond\Application\Content\Exceptions\PageNotFoundException;
use Diamond\Application\System\SystemService;
use Diamond\Infrastructure\Models\Page\Page;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class PublicPageFactory extends AbstractPageFactory
{
    /**
     * @var SystemService
     */
    protected $systemService;

    /**
     * @var ContentService
     */
    protected $contentService;

    /**
     * @var Request
     */
    protected $request;

    public function __construct(SystemService $systemService,
                                ContentService $contentService,
                                Request $request)
    {
        $this->systemService = $systemService;
        $this->contentService = $contentService;
        $this->request = $request;
    }

    public function createPage404(): Page
    {
        if (!$page = $this->contentService->getPage404()) {
            throw new PageNotFoundException($this->request->getPathInfo());
        }

        return $page;
    }

    public function createPage403(): Page
    {
        $access = 'Извините. Доступ к странице закрыт.';

        if(!$page = $this->contentService->getPageAccess()) {
            throw new IsRedirectResponseException(
                new Response($access, Response::HTTP_UNAUTHORIZED)
            );
        }

        return $page;
    }

    public function renderPage(Page $page): string
    {
        return $this->systemService->renderPage($page);
    }


}