<?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\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.getAllCa as="members"
 *                        organizationId="{settings.organizationId}">
 *          <f:debug>{members}</f:debug>
 *     </ot:members.getAllCa>
 *
 * @package Opentalent\OtTemplating\ViewHelpers
 */
class GetAllCaViewHelper 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(): void
    {
        $this->registerArgument(
            'as',
            'string',
            'Name of the returned array',
            true
        );
        $this->registerArgument(
            'organizationId',
            'integer',
            'Id of the current structure',
            true
        );
        $this->registerArgument(
            'groupByMissions',
            'bool',
            'If true, returns an array of the form [mission=>[members]], 
                       else the returned array is simply [members]',
            false,
            false
        );
    }

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

        // Missions to display (sorted)
        $missions = [
            'PRESIDENT',
            'HONORARY_PRESIDENT',
            'VICE_PRESIDENT',
            'VICE_PRESIDENT_OF_HONOR',
            'PRESIDENT_ASSISTANT',
            'HOUR_PRESIDENT',
            'SECRETARY',
            'ASSISTANT_SECRETARY',
            'TREASURER',
            'TREASURER_ASSISTANT',
            'MEMBER_OF_THE_BOARD',
            'MEMBER_OF_BOARD_OF_HONOR',
            'ACTIVE_COOPTED_BOARD_MEMBER',
            'ACTIVE_MEMBER_OF_THE_CA',
            'HONORARY_MEMBER',
            'YOUTH_REPRESENTATIVE'
        ];

        // 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 = [];
        }

        $members = array_filter($members, static function($m) use ($missions) {
            return in_array($m->getMission(), $missions, true);
        });

        // Sort by roles, then alphabetically by name
        usort($members,
            static function($a, $b) use ($missions) {
                if ($a->getMission() !== $b->getMission()) {
                    $ia = array_search($a->getMission(), $missions, true);
                    $ib = array_search($b->getMission(), $missions, true);
                    return $ia - $ib;
                }

                return strcmp($a->getName(), $b->getName());
            }
        );

        if ($groupByMissions && !empty($members)) {

            // Missions to display (sorted)
            $membersByMission = [];
            foreach ($missions as $mission) {
                $membersByMission[$mission] = [];
            }

            // Put members into their categories
            foreach ($members as $member) {
                if (array_key_exists($member->getMission(), $membersByMission)) {
                    $membersByMission[$member->getMission()][] = $member;
                }
            }

            // Remove empty sections and translate
            $members = [];
            foreach ($membersByMission as $mission => $groupMembers) {
                if (!$groupMembers) {
                    continue;
                }
                $members[ucfirst($this->translate($mission))] = $groupMembers;
            }
        }

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

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