<?php


namespace Diamond\Controllers;

use Twig\Error\RuntimeError;
use Core\Exceptions\ForbiddenAccessException;
use Core\Exceptions\IsRedirectResponseException;
use Core\Exceptions\ResponseException;
use Diamond\Application\Content\Exceptions\PageNotFoundException;
use Diamond\Application\System\SystemService;
use Diamond\Factory\AbstractPageFactory;
use Diamond\Infrastructure\Models\Page\Page;
use Exception;
use Symfony\Component\HttpFoundation\Response;

trait PageFactoryTrait
{
    /**
     * @var SystemService
     */
    protected $templateService;

    /**
     * @var AbstractPageFactory
     */
    protected $pageFactory;


    protected function getSystemPageFromException(Exception $ex): Response
    {

        if (is_a($ex, RuntimeError::class)) {
            $ex = $ex->getPrevious();
        }
        $status = 200;
        switch (true) {
            case is_a($ex, PageNotFoundException::class):

                $page = $this->pageFactory->createPage404();
                $status = 404;
                break;

            case is_a($ex, ForbiddenAccessException::class):
                $page = $this->pageFactory->createPage403();
                $status = 403;
                break;

            case is_a($ex, ResponseException::class):
                return $ex->getResponse();
                break;

            default:
                throw $ex;
        }

        try{
            return new Response($this->pageFactory->renderPage($page), $status);
        }
        catch (PageNotFoundException $ex){
            return new Response($this->pageFactory->renderPage($this->pageFactory->createPage404()), 404);
        }

    }
}