<?php

namespace ThimPress\ThimBlocks\Gutenberg;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

use ThimPress\ThimBlocks\Gutenberg\Blocks\AbstractBlockType;
use ThimPress\ThimBlocks\Helpers\Config;
use ThimPress\ThimBlocks\Helpers\Singleton;

/**
 * Class GutenbergHandleMain
 *
 * Handle register, render block template
 *
 * @since 1.0.0
 * @version 1.0.0
 */
class GutenbergHandleMain {
	use Singleton;

	/**
	 * Hooks handle block template
	 */
	public function init() {
		if ( ! wp_is_block_theme() ) {
			return;
		}

		add_filter( 'block_categories_all', array( $this, 'add_block_category' ), 10, 2 );
	}

	/**
	 * Register block, render content of block
	 * This function will be called on the "init" hook of WordPress.
	 *
	 * @return void
	 */
	public function register_blocks() {
		/**
		 * @var AbstractBlockType[] $blocks
		 */
		$blocks = Config::instance()->get( 'BlockElements', 'Gutenberg' );
		foreach ( $blocks as $block_template ) {
			// Register script to load on the Backend Edit.
			wp_register_script(
				$block_template->name, // Block name
				$block_template->source_js, // Block script
				array(), // Dependencies
				uniqid(), // Version,
				array( 'strategy' => 'defer' )
			);

			$args = array();
			foreach ( get_object_vars( $block_template ) as $property => $value ) {
				$args[ $property ] = $value;
			}

			$block_type = $block_template->name;
			/**
			 * register_block_type_from_metadata
			 *
			 * For case declare path to file block.json
			 */
			if ( ! empty( $block_template->path_block_json ) ) {
				$block_type = $block_template->path_block_json;
			}

			register_block_type(
				$block_type,
				$args
			);
		}
	}

	/**
	 * Register block category
	 *
	 * @param array $block_categories
	 * @param $editor_context
	 *
	 * @return array
	 */
	public function add_block_category( array $block_categories, $editor_context ) {
		$lp_block_categories = array(
			array(
				'slug'  => 'thim-block-category',
				'title' => __( 'Thim Blocks', 'thim-blocks' ),
				'icon'  => null,
			),
		);

		foreach ( $lp_block_categories as $block_category ) {
			array_unshift( $block_categories, $block_category );
		}

		return $block_categories;
	}

}
