<?php

declare(strict_types=1);

namespace FiloBlu\ExtBlackbirdMenuManager\Plugin;

use Blackbird\MenuManager\Api\NodeRepositoryInterface;
use Blackbird\MenuManager\Block\Adminhtml\Menu\Edit\Nodes;
use Blackbird\MenuManager\Controller\Adminhtml\Menu\Edit;
use Magento\Framework\Registry;

/**
 *
 */
class AddNodesAttributes
{
    /**
     * @var \Magento\Framework\Registry
     */
    private $registry;

    /**
     * @var \Blackbird\MenuManager\Api\NodeRepositoryInterface
     */
    private $nodeRepository;

    /**
     * @param \Magento\Framework\Registry $registry
     * @param \Blackbird\MenuManager\Api\NodeRepositoryInterface $nodeRepository
     */
    public function __construct(Registry $registry, NodeRepositoryInterface $nodeRepository)
    {
        $this->registry = $registry;
        $this->nodeRepository = $nodeRepository;
    }

    /**
     * @return string
     * @see \Blackbird\MenuManager\Block\Adminhtml\Menu\Edit\Nodes::renderNodes
     *
     */
    public function afterRenderNodes(Nodes $subject, $result)
    {
        $menu = $this->registry->registry(Edit::REGISTRY_CODE);

        if (!$menu || !$result) {
            return $result;
        }

        $nodes = $this->nodeRepository->getByMenu($menu->getId());

        if (preg_match_all('/<li.*id="node_(?P<id>\d+)" .*>/U', $result, $output) === false) {
            return $result;
        }

        foreach ($output['id'] as $nodeId) {
            $node = $nodes[$nodeId];
            $search = "id=\"node_$nodeId\"";
            $replace = sprintf('%s data-node_identifier="%s"', $search, $node->getIdentifier());
            $result = str_replace($search, $replace, $result);
        }

        return $result;
    }
}
