<?php
/**
 * Webkul Software.
 *
 * @category  Webkul
 * @package   Webkul_Agorae
 * @author    Webkul
 * @copyright Copyright (c) Webkul Software Private Limited (https://webkul.com)
 * @license   https://store.webkul.com/license.html
 */
namespace Webkul\Agorae\Block\Config;

use Magento\Framework\Registry;

/**
 * Adminhtml Agorae Block Config Category
 */
class Category extends \Magento\Config\Block\System\Config\Form\Field
{
    /**
     * @var  Registry
     */
    protected $_coreRegistry;

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

    /**
     * [_getElementHtml used to get HTML of an element in system config]
     *
     * @param  \Magento\Framework\Data\Form\Element\AbstractElement $element
     * @return string
     */
    protected function _getElementHtml(\Magento\Framework\Data\Form\Element\AbstractElement $element)
    {
        $html = $element->getElementHtml();
        $html .= '<script type="text/javascript">
            require(["jquery", "jquery/ui"], function () {
                jQuery(document).ready(function () {
                    if(jQuery("#'.$element->getHtmlId().'").length > 0){
                        if(jQuery("#'.$element->getHtmlId().' :selected").length > 2){
                            console.log("no");
                            jQuery("#' . $element->getHtmlId() . ' option:selected").prop("selected",false);
                            alert("Please select two top level categories.");
                        }
                    }
                    jQuery("#' . $element->getHtmlId() . '").on("change",function(){
                        if(jQuery("#'.$element->getHtmlId().' :selected").length < 2){
                            alert("Please select two top level categories.");
                        } else if(jQuery("#'.$element->getHtmlId().' :selected").length > 2){
                            jQuery("#' . $element->getHtmlId() . ' option:selected").prop("selected",false);
                            alert("Please select two top level categories.");
                        }
                    });
                });
            });
            </script>';
        return $html;
    }
}
