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

/*
 * 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\ContentRepository\Domain\Model\Node;
use Neos\ContentRepository\Domain\Model\NodeInterface;
use Neos\Flow\Cache\CacheManager;
use Neos\Flow\Core\Bootstrap;
use Neos\Flow\Package\Package as BasePackage;
use Newland\Toubiz\Poi\Neos\Controller\FilteredListsController;
use Newland\Toubiz\Poi\Neos\Listener\BuildUrls;
use Newland\Toubiz\Sync\Neos\Command\ArticlesCommandController;

class Package extends BasePackage
{
    public function boot(Bootstrap $bootstrap): void
    {
        $dispatcher = $bootstrap->getSignalSlotDispatcher();

        // TODO Move into class of its own
        $dispatcher->connect(
            Node::class,
            'beforeNodePropertyChange',
            function (NodeInterface $node, $propertyName) use ($bootstrap) {
                if (\Safe\preg_match('/(preselected)/', $propertyName)) {
                    /** @var CacheManager $cacheManager */
                    $cacheManager = $bootstrap->getObjectManager()->get(CacheManager::class);
                    $cache = $cacheManager->getCache(FilteredListsController::CACHE_NAME);
                    $cacheKey = sprintf(FilteredListsController::CACHE_KEY_TEMPLATE, $node->getIdentifier());
                    if ($cache->has($cacheKey)) {
                        $cache->remove($cacheKey);
                    }
                }
            }
        );

        $dispatcher->connect(
            ArticlesCommandController::class,
            'flush',
            BuildUrls::class,
            'run'
        );
    }
}
