<?php

namespace Yalogica\NinjaDraw\Blocks;

defined('ABSPATH') || exit;

use Yalogica\NinjaDraw\System\I18n;
use Yalogica\NinjaDraw\System\Shortcode;


class ImageBlock
{
  public function __construct()
  {
    add_action('init', [$this, 'init']);
  }

  public function init()
  {
    $block_type = register_block_type(NINJADRAW_PLUGIN_PATH . '/assets/components/gutenberg/image-block/block.json', ['render_callback' => [$this, 'renderBlock']]);

    wp_localize_script('ninjadraw-image-block-editor-script', 'NinjaDrawImageBlock', $this->getEditorGlobals());
    wp_localize_script('ninjadraw-image-block-view-script', 'NinjaDrawImageBlock', $this->getViewGlobals());
  }

  public function getEditorGlobals()
  {
    return [
      'data' => [
        'themes' => [
          'light' => esc_html__('Light', 'ninjadraw'),
          'dark' => esc_html__('Dark', 'ninjadraw'),
        ],
        'url_edit' => add_query_arg(['page' => 'ninjadraw', 'action' => 'edit'], admin_url('admin.php'))
      ],
      'i18n' => I18n::getTranslation(),
      'api' => [
        'nonce' => wp_create_nonce('wp_rest'),
        'url' => esc_url_raw(rest_url(NINJADRAW_PLUGIN_REST_URL)),
        'public_url' => esc_url_raw(rest_url(NINJADRAW_PLUGIN_PUBLIC_REST_URL))
      ]
    ];
  }

  public function getViewGlobals()
  {
    return [
      'api' => [
        'public_url' => esc_url_raw(rest_url(NINJADRAW_PLUGIN_PUBLIC_REST_URL))
      ]
    ];
  }

  public function renderBlock($attributes = [])
  {
    $attributes = array_change_key_case($attributes, CASE_LOWER);
    $defaults = [
      'itemid' => null,
      'themeid'  => 'light',
      'showtitle' => false,
      'classname' => null
    ];
    $attributes = shortcode_atts($defaults, $attributes);

    $attributes['id'] = $attributes['itemid'];
    $attributes['theme'] = $attributes['themeid'];
    $attributes['title'] = $attributes['showtitle'];
    $attributes['class'] = $attributes['classname'];

    return Shortcode::render($attributes);
  }
}
