<?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
    {
        if (array_key_exists('attributes', $query)) {
            foreach ($query['attributes'] as $attribute => $attributeValues) {
                if ($attribute === 'properties') {
                    $this->attributesIn = array_merge($this->attributesIn, $this->getProperties($attributeValues));
                } elseif ($attribute === 'labels') {
                    $this->attributesIn = array_merge($this->attributesIn, $this->getLabels($attributeValues));
                } elseif ($this->isMultiValue($attributeValues)) {
                    $this->attributesIn =
                        array_merge($this->attributesIn, $this->getMultiValue($attribute, $attributeValues));
                }
            }
        }

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

        return $this->attributesIn;
    }

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

    private function getLabels($attributeValues)
    {
        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'] ] ];
    }
}
