<?php
namespace Wpupgrader\Libraries\WordPress\Plugins\Core\Settings\Page\Callback;

use Wpupgrader\Libraries\WordPress\Plugins\Core\Settings\Page\Callback;

class Codemirror extends Callback
{
    public function callbackAction()
    {
        echo '<textarea cols="50" rows="10" class="regular-text" '.$this->getNameIdString().'>'.$this->getValue().'</textarea>'.$this->getTranslateLink().'<p>'.$this->getDescription().'</p>';

        if (function_exists('wp_enqueue_code_editor')) {
            // Enqueue code editor and settings for manipulating HTML.
            $settings = \wp_enqueue_code_editor([
                'type'   => !empty($this->args['mime']) ? $this->args['mime'] : 'htmlmixed',
                'jshint' => [
                    // The following are copied from <https://github.com/WordPress/wordpress-develop/blob/4.8.1/.jshintrc>.
                    'boss'     => true,
                    'curly'    => true,
                    'eqeqeq'   => true,
                    'eqnull'   => true,
                    'es3'      => true,
                    'expr'     => true,
                    'immed'    => true,
                    'noarg'    => true,
                    'nonbsp'   => true,
                    'onevar'   => true,
                    'quotmark' => ['single', 'double'],
                    'trailing' => true,
                    'undef'    => true,
                    'unused'   => true,
                    'browser'  => true,
                    'globals'  => [
                        '_'        => false,
                        'Backbone' => false,
                        'jQuery'   => true,
                        'JSON'     => false,
                        'wp'       => false,
                    ],
                ],
            ]);

            // Bail if user disabled CodeMirror.
            if (false === $settings) {
                return;
            }

            \wp_add_inline_script('code-editor',
                sprintf('jQuery(function(){
                        wp.codeEditor.initialize( "'.$this->getIdString().'", %s ).codemirror.setSize("100%%", "250px");
                    });', \wp_json_encode($settings)
                )
            );
        }
    }
}