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

/*
 * 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\FluidAdaptor\Core\ViewHelper\AbstractViewHelper;
use Newland\NeosCommon\Domain\Model\Topic;
use Newland\Toubiz\Poi\Neos\Domain\Repository\TopicRepository;

/**
 * Builds a query object for the given topic.
 */
class QueryViewHelper extends AbstractViewHelper
{

    public static function queryPathForTopic(Topic $topic, array $subPath = [], $addValueIfExists = true): array
    {
        switch ($topic->getType()) {
            case TopicRepository::TYPE_CATEGORY:
                $query = [ 'categories' ];
                break;
            case TopicRepository::TYPE_ATTRIBUTE:
                [, $propertyName] = explode(':', $topic->getCombinedIdentifier());
                $query = [ 'attributes', $propertyName ];
                break;
            default:
                $query = [];
                break;
        }

        if (array_key_exists($topic->getType(), $subPath)) {
            $appendItems = $subPath[$topic->getType()];
            if (is_string($appendItems)) {
                $appendItems = explode('.', $appendItems);
            }
            $query = array_merge($query, $appendItems);
        }

        if ($addValueIfExists) {
            $query[] = $topic->getValueOrIdentifier();
        }
        return $query;
    }

    public function render(Topic $topic): array
    {
        $path = static::queryPathForTopic(
            $topic,
            [ TopicRepository::TYPE_ATTRIBUTE => [ 'in' ] ]
        );

        $query = [];
        $current = &$query;
        foreach ($path as $part) {
            $current[$part] = [];
            $current = &$current[$part];
        }

        $current = $topic->getValueOrIdentifier();
        return $query;
    }
}
