<?php

namespace Opentalent\OtTemplating\ViewHelpers\Carousel;

use FluidTYPO3\Vhs\Traits\TemplateVariableViewHelperTrait;
use FluidTYPO3\Vhs\ViewHelpers\Page\Resources\FalViewHelper;
use Opentalent\OtCore\ViewHelpers\OtAbstractViewHelper;
use TYPO3\CMS\Core\Utility\GeneralUtility;

/**
 *   This view helper provides an an array of the FAL images files
 *   that can be used to display a carousel
 *
 *     {namespace ot=Opentalent\OtTemplating\ViewHelpers}
 *
 *     <ot:carousel.images as="images"
 *                         limit="5"
 *                         countAs="count">
 *          <f:debug>{images}</f:debug>
 *     </ot:carousel.images>
 *
 * @package Opentalent\OtTemplating\ViewHelpers
 */
class ImagesViewHelper extends OtAbstractViewHelper {

    use TemplateVariableViewHelperTrait;

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

    /**
     * -- 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(
            'limit',
            'integer',
            'Max number of images to return (mdefault: 5)',
            false,
            5
        );
        $this->registerArgument(
            'countAs',
            'string',
            "Name of the returned variable that contains the array's length",
            true,
            'count'
        );
    }

    /**
     *  -- This method is expected by Fluid --
     * Renders the content as html
     *
     * @return string
     * @throws \Exception
     */
    public function render()
    {

        // Get current settings
        $as = $this->arguments['as'];
        $limit = $this->arguments['limit'];
        $countAs = $this->arguments['countAs'];

        // Get images
        $falViewhelper = GeneralUtility::makeInstance(FalViewHelper::class);
        $pageUid = $GLOBALS['TSFE']->page;
        $falViewhelper->arguments['slide'] = -1;
        $falViewhelper->arguments['limit'] = null;
        $falViewhelper->arguments['slideCollectReverse'] = false;
        $falViewhelper->arguments['slideCollect'] = 0;
        $falViewhelper->arguments['asObjects'] = false;
        $resources = $falViewhelper->getResources($pageUid);

        $images = [];
        $count = 0;
        foreach ($resources as $resource) {
            if (preg_match('/^image\/.*/', $resource['mimetype'])) {
                $images[] = $resource;
                $count += 1;
                if ($count >= $limit) {
                    break;
                }
            }
        }

        $variables = [$as => $images, $countAs => $count];
        return $this->renderChildrenWithVariables($variables);
    }
}
