<?php
namespace Newland\Toubiz\Poi\Neos\Encoder;

/*
 * 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\Utility\Arrays;

class QueryToAttributesInEncoder
{
    /**
     * @var array
     */
    protected $attributesIn = [];

    public function encode(array $query): array
    {
        $attributesIn = [ [] ];

        if (array_key_exists('attributes', $query)) {
            foreach ($query['attributes'] as $attribute => $attributeValues) {
                if ($attribute === 'properties') {
                    $attributesIn[] = $this->getProperties($attributeValues);
                } elseif ($attribute === 'labels') {
                    $attributesIn[] = $this->getLabels($attributeValues);
                } elseif ($this->isMultiValue($attributeValues)) {
                    $attributesIn[] = $this->getMultiValue($attribute, $attributeValues);
                }
            }
        }

        if (array_key_exists('category', $query)) {
            $attributesIn[] = [ 'category' => array_values($query['category']) ];
        }

        return array_merge(...$attributesIn);
    }

    private function getProperties($attributeValues): array
    {
        return $this->getBoolean($attributeValues, 'properties');
    }

    private function getLabels($attributeValues): array
    {
        return $this->getBoolean($attributeValues, 'labels');
    }

    private function getBoolean(array $attributeValues, string $prefix): array
    {
        $values = (array) Arrays::getValueByPath($attributeValues, 'in');
        return [ $prefix => [ $values ] ];
    }

    private function isMultiValue($attributeValues): bool
    {
        return is_array(Arrays::getValueByPath($attributeValues, 'in'));
    }

    private function getMultiValue(string $attribute, array $attributeValues): array
    {
        return [ $attribute => [ $attributeValues['in'] ] ];
    }
}
