<?php
namespace Solwin\Verticalmenu\Controller\Adminhtml\Menu;

class MenusJson extends \Solwin\Verticalmenu\Controller\Adminhtml\Menu
{
    /**
     * JSON Result Factory
     * 
     * @var \Magento\Framework\Controller\Result\JsonFactory
     */
    protected $resultJsonFactory;

    /**
     * Layout Factory
     * 
     * @var \Magento\Framework\View\LayoutFactory
     */
    protected $layoutFactory;

    /**
     * constructor
     * 
     * @param \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
     * @param \Magento\Framework\View\LayoutFactory $layoutFactory
     * @param \Solwin\Verticalmenu\Model\MenuFactory $menuFactory
     * @param \Magento\Framework\Registry $coreRegistry
     * @param \Magento\Backend\App\Action\Context $context
     */
    public function __construct(
        \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
        \Magento\Framework\View\LayoutFactory $layoutFactory,
        \Solwin\Verticalmenu\Model\MenuFactory $menuFactory,
        \Magento\Framework\Registry $coreRegistry,
        \Magento\Backend\App\Action\Context $context
    ) {
        $this->resultJsonFactory = $resultJsonFactory;
        $this->layoutFactory     = $layoutFactory;
        parent::__construct($menuFactory, $coreRegistry, $context);
    }

    /**
     * Get tree node (Ajax version)
     *
     * @return \Magento\Framework\Controller\ResultInterface
     */
    public function execute()
    {
        if ($this->getRequest()->getParam('expand_all')) {
            $this->_getSession()->setSolwinVerticalmenuMenuIsTreeWasExpanded(true);
        } else {
            $this->_getSession()->setSolwinVerticalmenuMenuIsTreeWasExpanded(false);
        }
        $menuId = (int)$this->getRequest()->getPost('id');
        $resultJson = $this->resultJsonFactory->create();
        if ($menuId) {
            $this->getRequest()->setParam('menu_id', $menuId);

            $menu = $this->initMenu();
            if (!$menu) {
                /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
                $resultRedirect = $this->resultRedirectFactory->create();
                return $resultRedirect->setPath('solwin_verticalmenu/*/', ['_current' => true, 'menu_id' => null]);
            }
            /** @var \Magento\Framework\Controller\Result\Json $resultJson */
            return $resultJson->setJsonData(
                $this->layoutFactory->create()->createBlock('Solwin\Verticalmenu\Block\Adminhtml\Menu\Tree')
                    ->getTreeJson($menu)
            );
        }
        return $resultJson->setJsonData('[]');
    }
}
