<?php
namespace Newland\Toubiz\Poi\Neos\ViewHelpers\Collection\Attributes;

/*
 * This file is part of the "neos-viewhelpers" package.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 */

use Doctrine\Common\Collections\Collection;
use Neos\FluidAdaptor\Core\ViewHelper\AbstractViewHelper;
use Newland\Toubiz\Sync\Neos\Domain\Model\Attribute;

class BestSeasonViewHelper extends AbstractViewHelper
{
    /**
     * @var array
     */
    protected $attributes;

    /**
     * @var array
     */
    protected $values;

    /**
     * @var array
     */
    protected static $months = [ 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec' ];

    public function render(Collection $attributes): array
    {
        $bestSeason = [];

        $this->attributes = $attributes->getValues();
        $this->filterByName();
        $this->reduce();

        foreach (static::$months as $month) {
            $bestSeason[$month] = in_array($month, $this->values, true);
        }

        return $bestSeason;
    }

    /**
     * @param string $name
     */
    protected function filterByName($name = 'bestSeason'): void
    {
        if ($name) {
            $this->attributes = array_filter(
                $this->attributes,
                function (Attribute $attribute) use ($name) {
                    return $attribute->getName() === $name;
                }
            );
        }
    }

    protected function reduce(): void
    {
        $this->values = array_map(
            function (Attribute $attribute) {
                return $attribute->getData();
            },
            $this->attributes
        );
    }
}
