<?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 Newland\Toubiz\Poi\Neos\Domain\Repository\TopicRepository;

class TopicsToQueryEncoder
{
    /**
     * @var array
     */
    private $queryOverride = [];

    /**
     * @param string[] $topicIdentifiers
     * @return array
     */
    public function encode(array $topicIdentifiers = []): array
    {
        foreach ($topicIdentifiers as $topicIde) {
            $this->addQueryOverride($topicIde);
        }

        return $this->queryOverride;
    }

    protected function addQueryOverride(string $combinedIdentifier): void
    {
        if (strpos($combinedIdentifier, ':') === false) {
            return;
        }

        if (!preg_match(
            '/(?<type>category|attribute|tag):(?<identifier>[a-zA-Z0-9_\-]*)(:(?<value>.+))?/',
            $combinedIdentifier,
            $matches
        )
        ) {
            return;
        }

        switch ($matches['type']) {
            case TopicRepository::TYPE_CATEGORY:
                $this->addCategoryOverride($matches['identifier']);
                break;

            case TopicRepository::TYPE_ATTRIBUTE:
                if ($matches['value']) {
                    $this->addAttributeOverride($matches['identifier'], $matches['value']);
                }
                break;

            case TopicRepository::TYPE_TAG:
                $this->addAttributeOverride(
                    TopicRepository::TYPE_TAG,
                    explode(':', $combinedIdentifier, 2)[1]
                );
                break;
        }
    }

    private function addCategoryOverride(string $identifier): void
    {
        if (!isset($this->queryOverride['categories'])) {
            $this->queryOverride['categories'] = [];
        }
        $this->queryOverride['categories'][$identifier] = $identifier;
    }

    private function addAttributeOverride(string $identifier, string $value): void
    {
        if (!isset($this->queryOverride['attributes'])) {
            $this->queryOverride['attributes'] = [];
        }

        if (!isset($this->queryOverride['attributes'][$identifier])) {
            $this->queryOverride['attributes'][$identifier] = [ 'in' => [] ];
        }
        $this->queryOverride['attributes'][$identifier]['in'][] = $value;
    }
}
