<?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\Model\Organization;
use Opentalent\OtCore\Domain\Repository\OrganizationRepository;
use Opentalent\OtCore\Exception\ApiRequestException;

/**
 *   This view helper return the Organization object matching the given id
 *
 *     {namespace ot=Opentalent\OtTemplating\ViewHelpers}
 *
 *     <ot:organizations.getById as="organization"
 *                               organizationId="1">
 *          <f:debug>{organization}</f:debug>
 *     </ot:organizations.getById>
 *
 * @package Opentalent\OtTemplating\ViewHelpers
 */
class GetByIdViewHelper 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 method is expected by Fluid --
     * Renders the content as html
     *
     * @return string
     * @throws ApiRequestException
     */
    public function render()
    {
        $as = $this->arguments['as'];
        $organizationId = $this->arguments['organizationId'];

        try {
            $organization = $this->organizationRepository->findById($organizationId);
        } catch (ApiRequestException $e) {
            OtLogger::error(sprintf('API Error: %s', $e->getMessage()));
            $organization = new Organization();
            $organization->setName("<Erreur: impossible d'afficher le résultat>");
        }
        $variables = [$as => $organization];
        return $this->renderChildrenWithVariables($variables);
    }

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