<?php

namespace FiloBlu\Storelocator\Block\Adminhtml\Tags;

use Magento\Backend\Block\Widget\Context;
use Magento\Backend\Block\Widget\Form\Container;
use Magento\Framework\Phrase;
use Magento\Framework\Registry;

/**
 *
 */
class Edit extends Container
{
    /**
     * Core registry
     *
     * @var Registry
     */
    protected $coreRegistry = null;

    /**
     * @param Context $context
     * @param Registry $registry
     * @param array $data
     */
    public function __construct(
        Context $context,
        Registry $registry,
        array $data = []
    ) {
        parent::__construct($context, $data);
        $this->coreRegistry = $registry;
    }

    /**
     * Retrieve text for header element depending on loaded store
     *
     * @return Phrase
     */
    public function getHeaderText()
    {
        if ($this->coreRegistry->registry('storelocator_tag')->getId()) {
            return __("Edit Tag '%1'", $this->escapeHtml($this->coreRegistry->registry('storelocator_tag')->getName()));
        } else {
            return __('New Tag');
        }
    }

    /**
     * Initialize store edit block
     *
     * @return void
     */
    protected function _construct()
    {
        $this->_objectId = 'tag_id';
        $this->_blockGroup = 'FiloBlu_Storelocator';
        $this->_controller = 'adminhtml_tags';

        parent::_construct();

        if ($this->_isAllowedAction('FiloBlu_Storelocator::storelocator_save')) {
            $this->buttonList->update('save', 'label', __('Save Tag'));
            $this->buttonList->add(
                'saveandcontinue',
                [
                    'label' => __('Save and Continue Edit'),
                    'class' => 'save',
                    'data_attribute' => [
                        'mage-init' => [
                            'button' => ['event' => 'saveAndContinueEdit', 'target' => '#edit_form'],
                        ],
                    ]
                ],
                -100
            );
        } else {
            $this->buttonList->remove('save');
        }

        if ($this->_isAllowedAction('FiloBlu_Storelocator::storelocator_delete')) {
            $this->buttonList->update('delete', 'label', __('Delete Tag'));
        } else {
            $this->buttonList->remove('delete');
        }
    }

    /**
     * Check permission for passed action
     *
     * @param string $resourceId
     * @return bool
     */
    protected function _isAllowedAction($resourceId)
    {
        return $this->_authorization->isAllowed($resourceId);
    }

    /**
     * Getter of url for "Save and Continue" button
     * tab_id will be replaced by desired by JS later
     *
     * @return string
     */
    protected function _getSaveAndContinueUrl()
    {
        return $this->getUrl(
            'filoblustorelocatoradmin/*/save',
            ['_current' => true, 'back' => 'edit', 'active_tab' => '']
        );
    }
}