<?php

namespace Opentalent\OtTemplating\ViewHelpers\Utilities;

use Closure;
use Opentalent\OtCore\ViewHelpers\OtAbstractViewHelper;
use TYPO3Fluid\Fluid\Core\Rendering\RenderingContextInterface;

/**
 *   Transform an array into a paginated array
 *
 *     {namespace ot=Opentalent\OtTemplating\ViewHelpers}
 *
 *     {ot:utilities.paginateArray('[0, 1, ...]')}
 *
 * @package Opentalent\OtTemplating\ViewHelpers
 */
class PaginateArrayViewHelper extends OtAbstractViewHelper {

    /**
     * -- This method is expected by Fluid --
     * Declares the viewhelper's parameters
     */
    public function initializeArguments()
    {
        $this->registerArgument('array',
            'array',
            "The array",
            true);
        $this->registerArgument('itemsPerPage',
            'integer',
            "Number of items per page",
            false,
            10
        );
    }

    /**
     * -- This method is expected by Fluid --
     * Renders the content as html
     *
     * @param array $arguments
     * @param Closure $renderChildrenClosure
     * @param RenderingContextInterface $renderingContext
     * @return array
     */
    public static function renderStatic(
        array $arguments,
        Closure $renderChildrenClosure,
        RenderingContextInterface $renderingContext
    ) {
        $array = $arguments['array'];
        $itemsPerPage = $arguments['itemsPerPage'];

        $i = 0;
        $pageArray = [];
        $pages = [];

        foreach($array as $k => $v) {

            if ($i % $itemsPerPage == 0) {
                if ($pageArray) {
                    $pages[] = $pageArray;
                }
                $pageArray = [];
            }
            $pageArray[$k] = $v;
            $i++;
        }

        return $pages;
    }
}
