<?php


namespace Newland\Toubiz\Poi\Neos\Migration\Transformations;

use Neos\ContentRepository\Domain\Model\NodeData;
use Neos\ContentRepository\Migration\Transformations\AbstractTransformation;

class SplitTopicSelector extends AbstractTransformation
{
    /**
     * @var string
     */
    protected $propertyName;

    /**
     * @param string $propertyName
     * @return void
     */
    public function setProperty($propertyName): void
    {
        $this->propertyName = $propertyName;
    }

    /**
     * If the given node has the property this transformation should work on, this
     * returns true.
     *
     * @param NodeData $node
     * @return boolean
     */
    public function isTransformable(NodeData $node): bool
    {
        return $node->hasProperty($this->propertyName);
    }

    /**
     * Change the property on the given node.
     *
     * @param NodeData $node
     * @return NodeData
     */
    public function execute(NodeData $node): NodeData
    {
        $preselectedTopicsSelector = $node->getProperty($this->propertyName);
        $categories = [];
        $attributes = [];

        foreach ($preselectedTopicsSelector as $i => $item) {
            if (strpos($item, 'category:') !== false) {
                $categories[] = $item;
            } elseif (strpos($item, 'attribute:') !== false) {
                $attributes[] = $item;
            }
        }

        $node->setProperty('preselectedCategories', $categories);
        $node->setProperty('preselectedProperties', $attributes);
        $node->setProperty('preselectedTags', []);

        return $node;
    }
}
