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

class Edit extends \Solwin\Verticalmenu\Controller\Adminhtml\Menu
{
    
    /**
     * Page factory
     * 
     * @var \Magento\Framework\View\Result\PageFactory
     */
    protected $resultPageFactory;

    /**
     * Result JSON factory
     * 
     * @var \Magento\Framework\Controller\Result\JsonFactory
     */
    protected $resultJsonFactory;

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


    /**
     * Edit Menu page
     *
     * @return \Magento\Framework\Controller\ResultInterface
     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
     * @SuppressWarnings(PHPMD.NPathComplexity)
     */
    public function execute()
    {
        $parentId = (int)$this->getRequest()->getParam('parent');
        $menuId = (int)$this->getRequest()->getParam('menu_id');

        $menu = $this->initMenu();
        if (!$menu) {
            /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
            $resultRedirect = $this->resultRedirectFactory->create();
            return $resultRedirect->setPath('solwin_verticalmenu/*/', ['_current' => true, 'id' => null]);
        }

        /**
         * Check if we have data in session (if during Menu save was exception)
         */
        $data = $this->_getSession()->getSolwinVerticalmenuMenuData(true);
        if (isset($data['menu'])) {
            $menu->addData($data['menu']);
        }

        /** @var \Magento\Backend\Model\View\Result\Page $resultPage */
        $resultPage = $this->resultPageFactory->create();
        /**
         * Build response for ajax request
         */
        if ($this->getRequest()->getQuery('isAjax')) {
            // prepare breadcrumbs of selected Menu, if any
            $breadcrumbsPath = $menu->getPath();
            if (empty($breadcrumbsPath)) {
                // but if no Menu, and it is deleted - prepare breadcrumbs from path, saved in session
                //TODO: inject session instead of using objectManager
                $breadcrumbsPath = $this->_objectManager->get(
                    'Magento\Backend\Model\Auth\Session'
                )->getDeletedPath(
                        true
                    );
                if (!empty($breadcrumbsPath)) {
                    $breadcrumbsPath = explode('/', $breadcrumbsPath);
                    // no need to get parent breadcrumbs if deleting Menu level 1
                    if (count($breadcrumbsPath) <= 1) {
                        $breadcrumbsPath = '';
                    } else {
                        array_pop($breadcrumbsPath);
                        $breadcrumbsPath = implode('/', $breadcrumbsPath);
                    }
                }
            }

            $eventResponse = new \Magento\Framework\DataObject([
                'content' => $resultPage->getLayout()->getBlock('solwin.verticalmenu.menu.edit')->getFormHtml()
                    . $resultPage->getLayout()->getBlock('solwin.verticalmenu.menu.tree')
                        ->getBreadcrumbsJavascript($breadcrumbsPath, 'editingMenuBreadcrumbs'),
                'messages' => $resultPage->getLayout()->getMessagesBlock()->getGroupedHtml(),
                'toolbar' => $resultPage->getLayout()->getBlock('page.actions.toolbar')->toHtml()
            ]);
            $this->_eventManager->dispatch(
                'solwin_verticalmenu_menu_prepare_ajax_response',
                ['response' => $eventResponse, 'controller' => $this]
            );
            /** @var \Magento\Framework\Controller\Result\Json $resultJson */
            $resultJson = $this->resultJsonFactory->create();
            $resultJson->setHeader('Content-type', 'application/json', true);
            $resultJson->setData($eventResponse->getData());
            return $resultJson;
        }

        $resultPage->setActiveMenu('Solwin_Verticalmenu::menu');
        $resultPage->getConfig()->getTitle()->prepend(__('Menus'));
        $resultPage->getConfig()->getTitle()->prepend($menuId ? $menu->getMenu_title() : __('Menus'));
        $resultPage->addBreadcrumb(__('Manage Menus'), __('Manage Menus'));
        return $resultPage;
    }
}
