<?php

namespace Opentalent\OtTemplating\ViewHelpers\Members;

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

/**
 *   This view helper give access to an array named according to the 'as' variable
 *   and which contains the CA members of the structure classed by role
 *
 *     {namespace ot=Opentalent\OtTemplating\ViewHelpers}
 *
 *     <ot:members.getPresident as="president" organizationId="{settings.organizationId}">
 *          <f:debug>{president}</f:debug>
 *     </ot:members.getAllCa>
 *
 * @package Opentalent\OtTemplating\ViewHelpers
 */
class GetPresidentViewHelper extends OtAbstractViewHelper {

    use TemplateVariableViewHelperTrait;

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

    /**
     * @var MemberCaRepository
     *
     */
    protected MemberCaRepository $memberCaRepository;

    /**
     * -- 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 current structure',
            true
        );
    }

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

        // Get members of the structure (only CA members)
        try {
            $collection = $this->memberCaRepository->findByOrganizationId($organizationId);
            $members = $collection->getMembers();
        } catch (ApiRequestException $e) {
            OtLogger::error(sprintf('API Error: %s', $e->getMessage()));
            $members = [];
        }

        $president = null;
        foreach ($members as $member) {
            if ($member->getMission() === 'PRESIDENT') {
                $president = $member;
                break;
            }
        }

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

    /**
     * @param MemberCaRepository $memberCaRepository
     */
    public function injectMemberCaRepository(MemberCaRepository $memberCaRepository)
    {
        $this->memberCaRepository = $memberCaRepository;
    }
}
