<?php

namespace FiloBlu\ExtBlackbirdMenuManager\Block\NodeType;

use Blackbird\MenuManager\Api\Data\NodeInterface;
use Blackbird\MenuManager\Block\NodeType\AbstractNodeTypeFront;
use Magento\Backend\Block\Template\Context;

/**
 *
 */
class Group extends AbstractNodeTypeFront implements NodeInterface
{
    /**
     * Group constructor.
     * @param Context $context
     * @param array $data
     */
    public function __construct(
        Context $context,
        $data = []
    ) {
        parent::__construct($context, $data);
    }

    /**
     * @param array $nodes
     * @return void
     */
    public function fetchData(array $nodes)
    {
        $localNodes = [];
        //  $groupIds = [];
        foreach ($nodes as $node) {
            $localNodes[$node->getId()] = $node;
            // $groupIds[] = (int)$node->getContent();
        }
        $this->nodes = $localNodes;
    }

    /**
     * @param $nodeId
     * @param $level
     * @param $classes
     * @param $inlineCss
     * @param $childrenHtml
     * @param $childrenArray
     * @param $storeId
     * @return string
     */
    public function getHtml($nodeId, $level, $classes, $inlineCss, $childrenHtml, $childrenArray, $storeId)
    {
        $node = $this->nodes[$nodeId];

        $node->setUrlPath($this->getUrlNode($node, $childrenArray));

        $url = $this->getData('url');
        $classes = $this->getIsActiveClass($url, $node, $classes, $childrenArray);

        return parent::getHtml($nodeId, $level, $classes, $inlineCss, $childrenHtml, $childrenArray, $storeId);
    }

    /**
     * define the url of the node
     *
     * @param $node
     * @param $childrenArray
     * @return string
     */
    public function getUrlNode($node, $childrenArray)
    {
        $url = '/';
        if ($childrenArray && $node->getLinkFirstChild()) {
            $url = $childrenArray[0]->getUrlPath();
            $this->setUrl($url);
            $this->setLinkFirstChild(1);
        } else {
            $this->setUrl($url);
            $this->setLinkFirstChild(0);
        }
        return $url;
    }
}
