<?php

namespace Opentalent\OtTemplating\ViewHelpers\Organizations;

use FluidTYPO3\Vhs\Traits\TemplateVariableViewHelperTrait;
use Opentalent\OtCore\Domain\Repository\FederationStructureRepository;
use Opentalent\OtCore\Exception\ApiRequestException;
use Opentalent\OtCore\ViewHelpers\OtAbstractViewHelper;

/**
 *   This view helper returns all of the children federations as an ApiPagedCollection, without pagination
 *
 *     {namespace ot=Opentalent\OtTemplating\ViewHelpers}
 *
 *     <ot:organizations.getChildFederation as="organization"
 *                               organizationId="1">
 *          <f:debug>{organization}</f:debug>
 *     </ot:organizations.getChildFederation>
 *
 * @package Opentalent\OtTemplating\ViewHelpers
 */
class GetChildFederationViewHelper extends OtAbstractViewHelper {

    use TemplateVariableViewHelperTrait;

    /**
     * >> Required to prevent typo3 to escape the html output
     * @var boolean
     */
    protected $escapeOutput = false;

    /**
     * @var FederationStructureRepository
     *
     */
    protected $federationRepository;

    /**
     * -- This method is expected by Fluid --
     * Declares the viewhelper's parameters
     */
    public function initializeArguments()
    {
        $this->registerArgument(
            'as',
            'string',
            'Name of the returned array',
            true
        );
        $this->registerArgument(
            'parentId',
            'integer',
            'Id of the parent organization',
            true
        );
        $this->registerArgument(
            'itemsPerPage',
            'string',
            'Number of items per page',
            false,
            10
        );
    }

    /**
     * -- This method is expected by Fluid --
     * Renders the content as html
     *
     * @return string
     * @throws ApiRequestException
     */
    public function render()
    {
        $as = $this->arguments['as'];
        $parentId = $this->arguments['parentId'];
        $itemsPerPage = $this->arguments['itemsPerPage'];
        $page = $_REQUEST['page'] ?? 1;

        if ($itemsPerPage == 'all') {
            $itemsPerPage = 99999; // the 'all' keyword raise an error during the api call
            $page = 1;
        }

        $searchParams = ['itemsPerPage' => $itemsPerPage];

        $searchParams['filter[where][n1Id]'] = $parentId;
        $searchParams['filter[end][principalType]'] = 'FEDERATION';
        $organizations = $this->federationRepository->findChildrenById($parentId, $searchParams, $page, 1);

        $variables = [
            $as => $organizations
        ];
        return $this->renderChildrenWithVariables($variables);
    }

    /**
     * @param FederationStructureRepository $federationRepository
     */
    public function injectFederationRepository(FederationStructureRepository $federationRepository)
    {
        $this->federationRepository = $federationRepository;
    }
}
