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

class Save extends \Solwin\Verticalmenu\Controller\Adminhtml\Menu
{
    /**
     * Upload model
     * 
     * @var \Solwin\Verticalmenu\Model\Upload
     */
    protected $uploadModel;

    /**
     * Image model
     * 
     * @var \Solwin\Verticalmenu\Model\Menu\Image
     */
    protected $imageModel;

    /**
     * Result Raw Factory
     * 
     * @var \Magento\Framework\Controller\Result\RawFactory
     */
    protected $resultRawFactory;

    /**
     * Result Json Factory
     * 
     * @var \Magento\Framework\Controller\Result\JsonFactory
     */
    protected $resultJsonFactory;

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

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

    /**
     * run the action
     *
     * @return \Magento\Backend\Model\View\Result\Redirect
     */
    public function execute()
    {
        $data = $this->getRequest()->getPost('menu');
        $resultRedirect = $this->resultRedirectFactory->create();
        if ($data) {
            $menu = $this->initMenu();

            if (!$menu) {
                return $resultRedirect->setPath('solwin_verticalmenu/*/', ['_current' => true, 'id' => null]);
            }
            $menu->addData($data);
            $icon = $this->uploadModel->uploadFileAndGetName('icon', $this->imageModel->getBaseDir(), $data);
            $menu->setIcon($icon);
            $refreshTree = false;
            if (!$menu->getId()) {
                $parentId = $this->getRequest()->getParam('parent');
                if (!$parentId) {
                    $parentId = \Solwin\Verticalmenu\Model\Menu::TREE_ROOT_ID;
                }
                $parentMenu = $this->menuFactory->create()->load($parentId);
                $menu->setPath($parentMenu->getPath());
                $menu->setParentId($parentId);
            }

            $this->_eventManager->dispatch(
                'solwin_verticalmenu_menu_prepare_save',
                ['menu' => $menu, 'request' => $this->getRequest()]
            );

            try {
                $menu->save();
                $this->messageManager->addSuccess(__('You saved the Menu.'));
                $refreshTree = true;
            } catch (\Exception $e) {
                $this->messageManager->addError($e->getMessage());
                $this->_getSession()->setSolwinVerticalmenuMenuData($data);
                $refreshTree = false;
            }

            if ($this->getRequest()->getPost('return_session_messages_only')) {
                $menu->load($menu->getId());
                // to obtain truncated Menu Menu Title
                /** @var $block \Magento\Framework\View\Element\Messages */
                $block = $this->layoutFactory->create()->getMessagesBlock();
                $block->setMessages($this->messageManager->getMessages(true));

                /** @var \Magento\Framework\Controller\Result\Json $resultJson */
                $resultJson = $this->resultJsonFactory->create();
                return $resultJson->setData(
                    [
                        'messages' => $block->getGroupedHtml(),
                        'error' => !$refreshTree,
                        'menu' => $menu->toArray(),
                    ]
                );
            }
            $redirectParams = [
                '_current' => true,
                'menu_id' => $menu->getId()
            ];
            return $resultRedirect->setPath(
                'solwin_verticalmenu/*/edit',
                $redirectParams
            );
        }
        $redirectParams = ['_current' => true];
        return $resultRedirect->setPath(
            'solwin_verticalmenu/*/edit',
            $redirectParams
        );
    }
}
