<?php if ( ! defined( 'ABSPATH' ) ) { die; } // Cannot access directly.
/**
 *
 * Field: code_editor
 *
 * @since 1.0.0
 * @version 1.0.0
 *
 */
if ( ! class_exists( 'CGPS_Field_code_editor' ) ) {
  class CGPS_Field_code_editor extends CGPS_Fields {

    public $version = '';
    public $cdn_url = '';

    public function __construct( $field, $value = '', $unique = '', $where = '', $parent = '' ) {
      parent::__construct( $field, $value, $unique, $where, $parent );
    }

    public function render() {

      $default_settings = array(
        'tabSize'       => 2,
        'lineNumbers'   => true,
        'theme'         => 'default',
        'mode'          => 'htmlmixed',
        'cdnURL'        => '',
      );

      $settings = ( ! empty( $this->field['settings'] ) ) ? $this->field['settings'] : array();
      $settings = wp_parse_args( $settings, $default_settings );

      echo $this->field_before();
      echo '<textarea name="'. esc_attr( $this->field_name() ) .'"'. $this->field_attributes() .' data-editor="'. esc_attr( json_encode( $settings ) ) .'">'. $this->value .'</textarea>';
      echo $this->field_after();

    }

    public function enqueue() {

      $page = ( ! empty( $_GET[ 'page' ] ) ) ? sanitize_text_field( wp_unslash( $_GET[ 'page' ] ) ) : '';

      // Do not loads CodeMirror in revslider page.
      if ( in_array( $page, array( 'revslider' ) ) ) { return; }

      // 使用 WordPress 自带 CodeMirror（避免 CDN 慢导致后台白屏）
      if ( function_exists( 'wp_enqueue_code_editor' ) ) {
        // 尽可能按默认 mode 预加载必要脚本
        wp_enqueue_code_editor( array( 'type' => 'text/html' ) );
      }

      if ( function_exists( 'wp_enqueue_script' ) ) {
        wp_enqueue_script( 'code-editor' );
      }

      if ( function_exists( 'wp_enqueue_style' ) ) {
        wp_enqueue_style( 'wp-codemirror' );
      }

    }

  }
}
