<?php
namespace Newland\NeosCommon\SignalSlot;

/*
 * This file is part of the "neos-common" package.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 */

use Neos\ContentRepository\Domain\Model\NodeInterface;
use Neos\Flow\Annotations as Flow;
use Neos\Neos\Utility\NodeUriPathSegmentGenerator;

/**
 * Signal slots for the node model.
 */
class NodeSlot
{
    /**
     * @Flow\Inject()
     * @var NodeUriPathSegmentGenerator
     */
    protected $nodeUriPathSegmentGenerator;

    /**
     * Slot for the signals that the property of a node was changed.
     *
     * @param NodeInterface $node
     * @param string $propertyName name of the property that has been changed/added
     * @param mixed $oldValue the property value before it was changed or NULL if the property is new
     * @param mixed $newValue the new property value
     * @return void
     */
    public function nodePropertyChanged(NodeInterface $node, $propertyName, $oldValue, $newValue)
    {
        if ($propertyName !== 'title') {
            return;
        }

        if (\is_string($newValue)) {
            $this->updateUriPathSegmentBasedOnTitle($node, $newValue);
            $this->ensureUriPathSegmentDoesNotCollideWithOtherPages($node);
        }
    }

    private function updateUriPathSegmentBasedOnTitle(NodeInterface $node, string $title): void
    {
        $uriPathSegment = $this->nodeUriPathSegmentGenerator->generateUriPathSegment($node, $title);
        $node->setProperty('uriPathSegment', $uriPathSegment);
    }

    private function ensureUriPathSegmentDoesNotCollideWithOtherPages(NodeInterface $node): void
    {
        NodeUriPathSegmentGenerator::setUniqueUriPathSegment($node);
    }
}
