<?php

namespace WPGMZA\Integration;

if(!defined('ABSPATH'))
	return;

/**
 * This module integrates the plugin with the Gutenberg editor
 */
class Gutenberg extends \WPGMZA\Factory
{
	public $extendedBlocks;
	
	/**
	 * Constructor.
	 */
	public function __construct()
	{
		global $wpgmza;
		
		add_action('enqueue_block_assets', array( $this, 'onEnqueueBlockAssets' ));
		add_action('init', array( $this, 'onInit' ));

		if(function_exists('register_block_type')){
			$this->extendedBlocks = GutenbergExtended::createInstance();
		}
	}
	
	/**
	 * Enqueues assets to be used with the Gutenberg editor
	 */
	public function onEnqueueBlockAssets()
	{
		global $wpgmza;

		if(!is_admin()){
			return;
		}

		add_filter('wpgmza-get-core-script-dependencies', array($this, 'onFilterCoreDependencies'), 10, 1);

		$wpgmza->loadScripts(true);

		$version = $this->getVersion();

		$data = $wpgmza->getLocalizedData();
		wp_localize_script('wpgmza', 'WPGMZA_localized_data', $data);
		
		wp_enqueue_style(
			'wpgmza-gutenberg-integration', 
			plugin_dir_url(WPGMZA_FILE) . 'css/gutenberg.css', 
			'', 
			$version
		);

		wp_enqueue_style('dashicons');

        $blockAssets = array(
            "wp-blocks", 
            "wp-i18n",
            "wpgmza"
        );

        if(!wp_script_is('wp-edit-widgets') && !wp_script_is('wp-customize-widgets')){
            $blockAssets[] = "wp-editor";
        }

		/* Register the base module script */
		wp_register_script(
			"wpgmza-gutenberg-block", 
			plugin_dir_url(WPGMZA_FILE) . "/js/v8/3rd-party-integration/gutenberg/blocks/map/block.js", 
			$blockAssets,
			$version
		);
	}
	
	/**
	 * Called on the WordPress init action. This function strips out JS module generated by the babel compiler, for browser compatibility.
	 */
	public function onInit(){
		global $wpgmza;
		if(function_exists('register_block_type_from_metadata')){
			/* Old registration, now replaced by metadata load from the block.json
			/*register_block_type('gutenberg-wpgmza/block', array(
				'render_callback' => array(
					$this,
					'onRender'
				)
			));*/

			register_block_type_from_metadata(
				plugin_dir_path(WPGMZA_FILE) . 'js/v8/3rd-party-integration/gutenberg/blocks/map',
				array(
					'render_callback' => array($this, 'onRender')
				)
			);
		}
	}

	/**
	 * In some cases the block won't initialize because the API did not load correctly
	 * 
	 * Let's drop it, because blocks do not require them at all
	 * 
	 * @param array $dependencies
	 * 
	 * @return array
	 */
	public function onFilterCoreDependencies($dependencies){
		if(is_admin()){
			foreach($dependencies as $key => $handle){
				if(!empty($handle) && $handle === 'wpgmza_api_call'){
					unset($dependencies[$key]);
				}
			}
		}
		return $dependencies;
	}
	
	/**
	 * Called to render the plugins Gutenberg block front end.
	 * @param mixed[] $atts An array of attributes passed in from the editor.
	 */
	public function onRender($attr)
	{
		$attributes = array_merge(array('id' => 1), $attr);
		
		$str = "[wpgmza";
		
		foreach($attributes as $name => $value)
		{
			try {
				if(is_string($value)){
					$v = addslashes($value);
				} else if(is_array($value)){
					$v = implode(',', array_map('addslashes', $value));
				} else if(is_object($value)){
					$value = (array) $value;
					$v = implode(',', array_map('addslashes', $value));
				} else {
					$v = $value;
				}
			} catch (\Exception $ex){
				/* Skip, it's unlikely this is from us */
				continue;
			} catch (\Error $err){
				/* Skip, it's unlikely this is from us */
				continue;
			}
			
			$str .= " $name=\"" . addslashes($v) . "\"";
		}
		
		$str .= "]";
		
		return $str;
	}

	/**
     * Get a version string for scripts
     * 
     * @return string
    */
    protected function getVersion(){
        global $wpgmza;
        $version = $wpgmza->getBasicVersion();
        if(method_exists($wpgmza, 'getProVersion')){
            $version .= '+pro-' . $wpgmza->getProVersion();
        }

        return $version;
    }
}
