<?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 FullViewPropertiesToList extends AbstractTransformation
{

    public function execute(NodeData $node): NodeData
    {
        // Properties that are the same between the two node types.
        $this->setPropertyDefault($node, 'linkListTitle', '');
        $this->setPropertyDefault($node, 'eventScope', []);
        $this->setPropertyDefault($node, 'preselectedRegions', []);

        // Newly added properties
        $this->setPropertyDefault($node, 'preselectedCities', []);
        $this->setPropertyDefault($node, 'preselectedOrganizers', []);
        $this->setPropertyDefault($node, 'showHighlights', true);
        $this->setPropertyDefault($node, 'showTodaySeparately', false);

        // Migrated properties
        $preselectedTopics = $this->splitUpTopics($node->getProperty('preselectedTopics'));
        $this->setPropertyDefault($node, 'preselectedCategories', $preselectedTopics['categories'] ?? []);
        $this->setPropertyDefault($node, 'preselectedTags', $preselectedTopics['tags'] ?? []);

        return $node;
    }

    /** @param mixed $default */
    private function setPropertyDefault(NodeData $node, string $property, $default): void
    {
        if (!$node->hasProperty($property)) {
            $node->setProperty($property, $default);
        }
    }

    private function splitUpTopics(?array $topics): array
    {
        $tags = [];
        $categories = [];
        foreach ($topics ?? [] as $topic) {
            [ $type, $value ] = explode(':', $topic, 2);
            switch ($type) {
                case 'eventTag':
                    $tags[] = $value;
                    break;
                case 'category':
                    $categories[] = $value;
                    break;
            }
        }

        return [ 'tags' => $tags, 'categories' => $categories ];
    }
}
