<?php

namespace Webarian\Workshop\Block\Adminhtml\Workshop;

use Magento\Backend\Block\Widget\Context;
use Magento\Framework\Registry;

class Edit extends \Magento\Backend\Block\Widget\Form\Container
{
	protected $_coreRegistry = null;

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

	protected function _construct(){
		$this->_objectId = 'workshop_id';
		$this->_blockGroup = 'Webarian_Workshop';
		$this->_controller = 'adminhtml_workshop';

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

		if ($this->_isAllowedAction('Webarian_Workshop::workshop_delete')) {
			$this->buttonList->update('delete', 'label', __('Delete Workshop'));
		} else {
			$this->buttonList->remove('delete');
		}

		$this->buttonList->remove('back');
		$this->addButton(
			'back',
			[
				'label' => __('Back'),
				'onclick' => 'setLocation(\'' . $this->getBackUrl() . '\')',
				'class' => 'back back-form'
			],
			-1
		);

		$this->buttonList->remove('reset');
		$this->addButton(
			'reset',
			[
				'label' => __('Reset'),
				'onclick' => 'setLocation(window.location.href)',
				'class' => 'reset reset-form'
			],
			-1
		);
	}

	public function getHeaderText()
	{
		if ($this->_coreRegistry->registry('workshop_workshop')->getId()) {
			return __("Edit Workshop '%1'", $this->escapeHtml($this->_coreRegistry->registry('workshop_workshop')->getTitle()));
		} else {
			return __('Add New Workshop');
		}
	}

	protected function _getSaveAndContinueUrl()
	{
		return $this->getUrl('workshop/*/save', ['_current' => true, 'back' => 'edit', 'active_tab' => '{{tab_id}}']);
	}

	protected function _isAllowedAction($resourceId)
	{
		return $this->_authorization->isAllowed($resourceId);
	}

	protected function _prepareLayout()
	{
		$this->_formScripts[] = "
            function toggleEditor() {
                if (tinyMCE.getInstanceById('workshop_content') == null) {
                    tinyMCE.execCommand('mceAddControl', false, 'workshop_content');
                } else {
                    tinyMCE.execCommand('mceRemoveControl', false, 'workshop_content');
                }
            }
        ";
		return parent::_prepareLayout();
	}
}