<?php

namespace Opentalent\OtTemplating\ViewHelpers\Organizations;

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

/**
 *   This viewhelper formats an array of Organization / FederationStructures objects into an json-array
 *   containing the data needed by the leaflet markers: [{id: 0, long: 0, lat: 0, label: ''}, ...]
 *
 *     {namespace ot=Opentalent\OtTemplating\ViewHelpers}
 *
 *     <ot:organizations.asGeoMarkersArray structures="structures">
 *          <f:debug>{organization}</f:debug>
 *     </ot:organizations.asGeoMarkersArray>
 *
 * @package Opentalent\OtTemplating\ViewHelpers
 */
class AsGeoMarkersArrayViewHelper extends OtAbstractViewHelper {

    use TemplateVariableViewHelperTrait;

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

    /**
     * -- This method is expected by Fluid --
     * Declares the viewhelper's parameters
     */
    public function initializeArguments()
    {
        $this->registerArgument(
            'structures',
            'array',
            'Array of Organization or FederationStructure objects',
            true
        );
    }

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

        $markers = [];
        foreach ($structures as $structure)  {
            if ($structure->getLongitude() && $structure->getLatitude()) {
                $markers[] = [
                    'id' => $structure->getId(),
                    'long' => $structure->getLongitude(),
                    'lat' => $structure->getLatitude(),
                    'label' => $structure->getName() ?? ""
                ];
            }
        }

        return json_encode($markers);
    }

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