<?php
namespace Solwin\Verticalmenu\Block\Adminhtml\Menu\Edit;

class Form extends \Solwin\Verticalmenu\Block\Adminhtml\Menu\AbstractMenu
{
    /**
     * Additional buttons
     * 
     * @var array
     */
    protected $additionalButtons = [];

    /**
     * Block template
     * 
     * @var string
     */
    protected $_template = 'menu/edit/form.phtml';

    /**
     * JSON encoder
     * 
     * @var \Magento\Framework\Json\EncoderInterface
     */
    protected $jsonEncoder;

    /**
     * constructor
     * 
     * @param \Magento\Framework\Json\EncoderInterface $jsonEncoder
     * @param \Magento\Framework\Registry $registry
     * @param \Solwin\Verticalmenu\Model\ResourceModel\Menu\Tree $menuTree
     * @param \Solwin\Verticalmenu\Model\MenuFactory $menuFactory
     * @param \Solwin\Verticalmenu\Model\ResourceModel\Menu\CollectionFactory $menuCollectionFactory
     * @param \Magento\Backend\Block\Widget\Context $context
     * @param array $data
     */
    public function __construct(
        \Magento\Framework\Json\EncoderInterface $jsonEncoder,
        \Magento\Framework\Registry $registry,
        \Solwin\Verticalmenu\Model\ResourceModel\Menu\Tree $menuTree,
        \Solwin\Verticalmenu\Model\MenuFactory $menuFactory,
        \Solwin\Verticalmenu\Model\ResourceModel\Menu\CollectionFactory $menuCollectionFactory,
        \Magento\Backend\Block\Widget\Context $context,
        array $data = []
    )
    {
        $this->jsonEncoder = $jsonEncoder;
        parent::__construct($registry, $menuTree, $menuFactory, $menuCollectionFactory, $context, $data);
    }

    /**
     * @return $this
     */
    protected function _prepareLayout()
    {
        $menu   = $this->getMenu();
        $menuId = (int)$menu->getId();
        // 0 when we create Menu, otherwise some value for editing Menu

        $this->setChild(
            'tabs',
            $this->getLayout()->createBlock('Solwin\Verticalmenu\Block\Adminhtml\Menu\Edit\Tabs', 'tabs')
        );

        // Save button
        $this->addButton(
            'save',
            [
                'id' => 'save',
                'label' => __('Save Menu'),
                'class' => 'save primary save-menu',
                'data_attribute' => [
                    'mage-init' => [
                        'Solwin_Verticalmenu/menu/edit' => [
                            'url' => $this->getSaveUrl(),
                            'ajax' => true
                        ]
                    ]
                ]
            ]
        );

        // Delete button
        if ($menuId && !in_array($menuId, $this->getRootIds())) {
            $this->addButton(
                'delete',
                [
                    'id' => 'delete',
                    'label' => __('Delete Menu'),
                    'onclick' => "menuDelete('" . $this->getUrl(
                        'solwin_verticalmenu/*/delete',
                        ['_current' => true]
                    ) . "')",
                    'class' => 'delete'
                ]
            );
        }

        // Reset button
        $resetPath = $menuId ? 'solwin_verticalmenu/*/edit' : 'solwin_verticalmenu/*/add';
        $this->addButton(
            'reset',
            [
                'id' => 'reset',
                'label' => __('Reset'),
                'onclick' => "menuReset('" . $this->getUrl($resetPath, ['_current' => true]) . "',false)",
                'class' => 'reset'
            ]
        );

        return parent::_prepareLayout();
    }

    /**
     * Retrieve additional buttons html
     *
     * @return string
     */
    public function getAdditionalButtonsHtml()
    {
        $html = '';
        foreach ($this->additionalButtons as $childName) {
            $html .= $this->getChildHtml($childName);
        }
        return $html;
    }

    /**
     * Add additional button
     *
     * @param string $alias
     * @param array $config
     * @return $this
     */
    public function addAdditionalButton($alias, $config)
    {
        if (isset($config['name'])) {
            $config['element_name'] = $config['name'];
        }
        if ($this->hasToolbarBlock()) {
            $this->addButton($alias, $config);
        } else {
            $this->setChild(
                $alias . '_button',
                $this->getLayout()->createBlock('Magento\Backend\Block\Widget\Button')->addData($config)
            );
            $this->additionalButtons[$alias] = $alias . '_button';
        }

        return $this;
    }

    /**
     * Remove additional button
     *
     * @param string $alias
     * @return $this
     */
    public function removeAdditionalButton($alias)
    {
        if (isset($this->additionalButtons[$alias])) {
            $this->unsetChild($this->additionalButtons[$alias]);
            unset($this->additionalButtons[$alias]);
        }

        return $this;
    }

    /**
     * @return string
     */
    public function getTabsHtml()
    {
        return $this->getChildHtml('tabs');
    }

    /**
     * @return \Magento\Framework\Phrase|string
     */
    public function getHeader()
    {
        if ($this->getMenuId()) {
            return $this->getMenuMenu_title();
        } else {
            $parentId = (int)$this->getRequest()->getParam('parent');
            if ($parentId && $parentId != \Solwin\Verticalmenu\Model\Menu::TREE_ROOT_ID) {
                return __('New Child Menu');
            } else {
                return __('New Root Menu');
            }
        }
    }

    /**
     * @param array $args
     * @return string
     */
    public function getDeleteUrl(array $args = [])
    {
        $params = ['_current' => true];
        $params = array_merge($params, $args);
        return $this->getUrl('solwin_verticalmenu/*/delete', $params);
    }

    /**
     * Return URL for refresh input element 'path' in form
     *
     * @param array $args
     * @return string
     */
    public function getRefreshPathUrl(array $args = [])
    {
        $params = ['_current' => true];
        $params = array_merge($params, $args);
        return $this->getUrl('solwin_verticalmenu/*/refreshPath', $params);
    }

    /**
     * @return bool
     */
    public function isAjax()
    {
        return $this->_request->isXmlHttpRequest() || $this->_request->getParam('isAjax');
    }

    /**
     * Get parent Menu id
     *
     * @return int
     */
    public function getParentMenuId()
    {
        return (int)$this->templateContext->getRequest()->getParam('parent');
    }

    /**
     * Get Menu  id
     *
     * @return int
     */
    public function getMenuId()
    {
        return (int)$this->templateContext->getRequest()->getParam('menu_id');
    }

    /**
     * Add button block as a child block or to global Page Toolbar block if available
     *
     * @param string $buttonId
     * @param array $data
     * @return $this
     */
    protected function addButton($buttonId, array $data)
    {
        $childBlockId = $buttonId . '_button';
        $button = $this->getButtonChildBlock($childBlockId);
        $button->setData($data);
        $block = $this->getLayout()->getBlock('page.actions.toolbar');
        if ($block) {
            $block->setChild($childBlockId, $button);
        } else {
            $this->setChild($childBlockId, $button);
        }
    }

    /**
     * @return bool
     */
    protected function hasToolbarBlock()
    {
        return $this->getLayout()->isBlock('page.actions.toolbar');
    }

    /**
     * Adding child block with specified child's id.
     *
     * @param string $childId
     * @param null|string $blockClassName
     * @return \Magento\Backend\Block\Widget
     */
    protected function getButtonChildBlock($childId, $blockClassName = null)
    {
        if (null === $blockClassName) {
            $blockClassName = 'Magento\Backend\Block\Widget\Button';
        }
        return $this->getLayout()->createBlock($blockClassName, $this->getNameInLayout() . '-' . $childId);
    }
}
