<?php

namespace FiloBlu\ExtBlackbirdMenuManager\Block\NodeType;

use Blackbird\MenuManager\Block\NodeType\AbstractNodeTypeFront;
use Magento\Backend\Block\Template\Context;
use Magento\Catalog\Api\CategoryRepositoryInterface;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Profiler;

/**
 *
 */
class Subcategory extends AbstractNodeTypeFront
{
    /**
     * @var array
     */
    protected $categoryUrls;

    /**
     * @var \Magento\Catalog\Api\CategoryRepositoryInterface
     */
    protected $_categoryRepositoryInterface;
    /**
     * @var ResourceConnection
     */
    private $connection;

    /**
     * @var Profiler
     */
    private $profiler;

    /**
     * @param \Magento\Backend\Block\Template\Context $context
     * @param \Magento\Framework\App\ResourceConnection $connection
     * @param \Magento\Framework\Profiler $profiler
     * @param \Magento\Catalog\Api\CategoryRepositoryInterface $categoryRepositoryInterFace
     * @param array $data
     */
    public function __construct(
        Context $context,
        ResourceConnection $connection,
        Profiler $profiler,
        CategoryRepositoryInterface $categoryRepositoryInterFace,
        $data = []
    ) {
        $this->connection = $connection;
        $this->profiler = $profiler;
        $this->_categoryRepositoryInterface = $categoryRepositoryInterFace;
        parent::__construct($context, $data);
    }

    /**
     * @param array $nodes
     * @return void
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function fetchData(array $nodes)
    {
        $this->profiler::start(__METHOD__);
        $localNodes = [];
        $categoryIds = [];
        foreach ($nodes as $node) {
            $localNodes[$node->getId()] = $node;
            $categoryIds[] = (int)$node->getContent();
        }

        $this->nodes = $localNodes;
        $table = $this->connection->getTableName('url_rewrite');
        $select = $this->connection->getConnection('read')->select()->from($table, ['entity_id', 'request_path']
            )->where('entity_type = ?', 'category')->where(
                'store_id = ?',
                $this->_storeManager->getStore()->getId()
            )->where('entity_id IN (' . implode(',', $categoryIds) . ')');
        $this->categoryUrls = $this->connection->getConnection('read')->fetchPairs($select);
        $this->profiler::stop(__METHOD__);
    }

    /**
     * @param $nodeId
     * @param $level
     * @param $classes
     * @param $inlineCss
     * @param $childrenHtml
     * @param $childrenArray
     * @param $storeId
     * @return string
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function getHtml($nodeId, $level, $classes, $inlineCss, $childrenHtml, $childrenArray, $storeId)
    {
        $node = $this->nodes[$nodeId];
        $node->setUrlPath($this->getUrlNode($node));

        $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
     * @return mixed
     * @throws NoSuchEntityException
     */
    public function getUrlNode($node)
    {
        try {
            $category = $this->_categoryRepositoryInterface->get($node->getEntityId());
            $url = $category->getUrl();

            $this->setSubmenu($this->getSubMenuData($category));
        } catch (NoSuchEntityException $e) {
            $url = $this->_storeManager->getStore()->getBaseUrl();
        }

        $this->setUrl($url);
        return $url;
    }

    /**
     * @param $category
     * @return array
     */
    public function getSubMenuData($category)
    {
        $returnarray = [];

        $childrenCategories = $category->getChildrenCategories();
        foreach ($childrenCategories as $subCat) {
            $returnarray[] = [
                'name' => $subCat->getName(),
                'url'  => $subCat->getUrl()
            ];
        }

        return $returnarray;
    }

    /**
     * method to prepare the template
     *
     * @param $type
     * @param $menuIdentifier
     * @return $this
     */
    public function prepareTemplate($type, $menuIdentifier)
    {
        //Custom template if existing
        //$menuidentifier is the identifier of the menu used for every pages defined in the default.xml
        $this->setTemplate(
            'FiloBlu_ExtBlackbirdMenuManager::menu/view/' . $menuIdentifier . '/nodetype/' . $type . '.phtml'
        );

        if (!$this->getTemplateFile()) {
            //default case
            $this->setTemplate('FiloBlu_ExtBlackbirdMenuManager::menu/view/default/nodetype/' . $type . '.phtml');
        }

        return $this;
    }
}