<?php declare(strict_types=1);

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

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

class TopicToIdentifiers extends AbstractTransformation
{
    public function execute(NodeData $node): NodeData
    {
        $node = $this->splitTopics($node, 'preselectedTopics');
        $this->replacePrefixes($node, 'preselectedTopics');
        $this->replacePrefixes($node, 'preselectedCategories');
        $this->replacePrefixes($node, 'preselectedProperties');

        return $node;
    }

    private function replacePrefixes(NodeData $node, string $property): void
    {
        if (!$node->hasProperty($property)) {
            return;
        }

        $values = $node->getProperty($property);
        if (!\is_array($values)) {
            return;
        }

        foreach ($values as $index => $value) {
            $values[$index] = preg_replace('/^(category|attribute|tag):/', '', $value);
        }
        $node->setProperty($property, $values);
    }

    private function splitTopics(NodeData $node, string $property): NodeData
    {
        $values = $node->getProperty($property);

        $categories = [];
        $attributes = [];
        $tags = [];

        if (!\is_array($values)) {
            return $node;
        }
        foreach ($values as $i => $item) {
            if (strpos($item, 'category:') !== false) {
                $categories[] = $item;
            } elseif (strpos($item, 'attribute:') !== false) {
                $attributes[] = $item;
            } elseif (strpos($item, 'tag:') !== false) {
                $tags[] = $item;
            }
        }

        $node->setProperty('preselectedCategories', $categories);
        $node->setProperty('preselectedProperties', $attributes);
        $node->setProperty('preselectedTags', $tags);
        return $node;
    }
}
