<?php

namespace Opentalent\OtTemplating\ViewHelpers\Organizations;

use FluidTYPO3\Vhs\Traits\TemplateVariableViewHelperTrait;
use Opentalent\OtCore\Logging\OtLogger;
use Opentalent\OtCore\ViewHelpers\OtAbstractViewHelper;
use Opentalent\OtCore\Domain\Repository\OrganizationRepository;
use Opentalent\OtCore\Exception\ApiRequestException;

/**
 *   This view helper returns the organization children structures as an ApiPagedCollection
 *
 *     {namespace ot=Opentalent\OtTemplating\ViewHelpers}
 *
 *     <ot:organizations.getChildren as="organization"
 *                               organizationId="1">
 *          <f:debug>{organization}</f:debug>
 *     </ot:organizations.getChildren>
 *
 * @package Opentalent\OtTemplating\ViewHelpers
 */
class GetChildrenViewHelper extends OtAbstractViewHelper {

    use TemplateVariableViewHelperTrait;

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

    /**
     * @var OrganizationRepository
     *
     */
    protected $organizationRepository;

    /**
     * -- 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(
            'organizationId',
            'integer',
            'Id of the organization',
            true
        );
        $this->registerArgument(
            'page',
            'integer',
            'Page number',
            false,
            1
        );
    }

    /**
     * -- This method is expected by Fluid --
     * Renders the content as html
     *
     * @return string
     */
    public function render()
    {
        $as = $this->arguments['as'];
        $organizationId = $this->arguments['organizationId'];

        $page = $_REQUEST['page'] ?? 1;

        $searchParams = [];
        if($_REQUEST['search-loc']) {
            $searchParams['where'] = $_REQUEST['search-loc'];
        }

        try {
            $organizations = $this->organizationRepository->findChildrenById(
                $organizationId,
                $searchParams,
                $page
            );
        } catch (ApiRequestException $e) {
            OtLogger::error(sprintf('API Error: %s', $e->getMessage()));
            $organizations = [];
        }

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

    /**
     * @param OrganizationRepository $organizationRepository
     */
    public function injectOrganizationRepository(OrganizationRepository $organizationRepository)
    {
        $this->organizationRepository = $organizationRepository;
    }
}
