<?php
namespace Newland\Toubiz\Poi\Neos\Filter\Items;

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

use Neos\Flow\Annotations as Flow;
use Newland\NeosFiltering\Items\CheckboxList;
use Newland\Toubiz\Sync\Neos\Domain\Model\Article;
use Newland\Toubiz\Sync\Neos\Domain\Model\ZipCode;
use Newland\Toubiz\Sync\Neos\Domain\Repository\ArticleRepository;

class CityZipList extends CheckboxList
{
    /**
     * @var ArticleRepository
     * @Flow\Inject()
     */
    protected $articleRepository;

    public function setCombine(string $combine): void
    {
        if ($combine === static::$AND) {
            throw new \InvalidArgumentException('This filter item does not support being combined with AND');
        }
        parent::setCombine($combine);
    }

    protected function getStateValuesForQuery(): array
    {
        $identifiers = parent::getStateValuesForQuery();

        if (empty($identifiers)) {
            return [];
        }

        $cities = $this->articleRepository->findByIdentifiers($identifiers);

        $zipCodes = [ [] ];
        /** @var Article $city */
        foreach ($cities as $city) {
            $cityData = $city->getCityData();
            if ($cityData) {
                $zips = array_map(
                    function (ZipCode $zipCode) {
                        return $zipCode->getZipCode();
                    },
                    $cityData->getZipCodes()->toArray()
                );
                $zipCodes[] = $zips;
            }
        }

        $values = array_merge(... $zipCodes);

        return array_filter(
            $values,
            function (string $zipCode) {
                return !empty($zipCode) && $zipCode !== '0';
            }
        );
    }
}
