<?php

namespace Opentalent\OtTemplating\ViewHelpers;


use Closure;
use Opentalent\OtCore\Website\OtPageRepository;
use Opentalent\OtCore\ViewHelpers\OtAbstractViewHelper;
use Opentalent\OtTemplating\ViewHelpers\RootPage\GetIdViewHelper;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Object\ObjectManager;
use TYPO3Fluid\Fluid\Core\Rendering\RenderingContextInterface;

/**
 * Returns the uid of the first page with the given template in the current website, or null if none
 *
 *     {namespace ot=Opentalent\OtTemplating\ViewHelpers}
 *
 *     {ot:page.getFirstWithTemplate(template: 'foo')}
 *
 * @package Opentalent\OtTemplating\ViewHelpers
 */
class FirstWithTemplateViewHelper extends OtAbstractViewHelper
{

    /**
     * -- This method is expected by Fluid --
     * Declares the viewhelper's parameters
     */
    public function initializeArguments()
    {
        $this->registerArgument(
            'template',
            'string',
            "The template's name",
            true
        );
    }

    /**
     * -- 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
    ) {
        $rootId = GetIdViewHelper::renderStatic(
            $arguments,
            $renderChildrenClosure,
            $renderingContext
        );

        $pageRepository = GeneralUtility::makeInstance(ObjectManager::class)->get(OtPageRepository::class);

        $subpages = $pageRepository->getAllSubpagesForPage($rootId);

        $templateName = 'OpenTalent.OtTemplating->' . $arguments['template'];

        foreach ($subpages as $page) {
            if ($page['tx_fed_page_controller_action'] === $templateName
                & $page['deleted'] === 0
                & $page['hidden'] === 0
            ) {
                return $page['uid'];
            }
        }
        return null;
    }

}
