<?php
namespace Avirtum\GutenDraw\Blocks;

defined( 'ABSPATH' ) || exit;

use Avirtum\GutenDraw\System\I18n;
use Avirtum\GutenDraw\System\Shortcode;

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

    public function init() {
        register_block_type( GUTENDRAW_PLUGIN_PATH . '/assets/block/block.json', [ 'render_callback' => [ $this, 'renderBlock' ] ] );

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

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

    public function getViewGlobals() {
        return [
            'api' => [
                'public_url' => esc_url_raw( rest_url( GUTENDRAW_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 );
    }
}