<?php

namespace Opentalent\OtTemplating\ViewHelpers\RootPage;

use Closure;
use FluidTYPO3\Vhs\Service\PageService;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Object\ObjectManager;
use TYPO3Fluid\Fluid\Core\Rendering\RenderingContextInterface;
use TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper;

/**
 * Viewhelper to retrieve the Id of the current site root page
 * Call it in fluid templates with:
 *
 *     {namespace ot=Opentalent\OtTemplating\ViewHelpers}
 *
 *     {ot:rootPage.getId()}
 *
 * @package Opentalent\OtTemplating\ViewHelpers
 */
class GetIdViewHelper extends AbstractViewHelper
{
    /**
     * -- This method is expected by Fluid --
     * Renders the content as html
     *
     * @param array $arguments
     * @param Closure $renderChildrenClosure
     * @param RenderingContextInterface $renderingContext
     * @return int|null
     */
    public static function renderStatic(
        array $arguments,
        Closure $renderChildrenClosure,
        RenderingContextInterface $renderingContext
    ) {
        $pageUid = $GLOBALS['TSFE']->id;
        $pageService = GeneralUtility::makeInstance(ObjectManager::class)->get(PageService::class);
        $rootLine = $pageService->getRootLine($pageUid);

        for (end($rootLine); key($rootLine)!==null; prev($rootLine)){
            $page = current($rootLine);
            if ($page['is_siteroot'] == 1) {
                return $page['uid'];
            }
        }
        return $rootLine[0]['uid'];
    }
}
