<?php

namespace Greyd\Query;

if ( ! defined( 'ABSPATH' ) ) exit;

new Enqueue($config);
class Enqueue {

	/**
	 * Holds the plugin config
	 */
	private $config;

	/**
	 * Constructor
	 */
	public function __construct( $config ) {

		// check if Gutenberg is active.
		if (!function_exists('register_block_type')) return;

		// set config
		$this->config = (object) $config;

		// setup
		if (!function_exists('get_plugin_data')) require_once(ABSPATH . '/wp-admin/includes/plugin.php');
		$this->config->plugin_version = get_plugin_data($this->config->plugin_file)['Version'];
		$this->config->assets_url = trailingslashit(plugin_dir_url(__FILE__));

		// enqueue scripts
		add_action( 'wp_enqueue_scripts', array( $this, 'add_frontend_scripts' ) );
		if ( is_admin() ) {
			/**
			 * 'enqueue_block_assets' action should be used here. 
			 * @see features/blocks/enqueue.php
			 */
			$action = \Greyd\Helper::is_active_plugin('gutenberg/gutenberg.php') ? 'enqueue_block_assets' : 'current_screen';
			add_action( $action, array($this, 'register_block_editor_styles') );
			add_action( 'enqueue_block_editor_assets', array($this, 'register_block_editor_scripts') );
		}
		
		add_filter( 'greyd_blocks_render_block', array($this, 'render_block'), 10, 2 );
	}

	/**
	 * Enqueue frontend scripts.
	 * @action wp_enqueue_scripts
	 */
	public function add_frontend_scripts() {

		$version = $this->config->plugin_version;
	
		// register the post slider script
		if ( ! wp_style_is( 'greyd-query-postslider-script', 'registered') ) {
			wp_register_script(
				'greyd-query-postslider-script',
				$this->config->assets_url.'assets/js/post-slider.js',
				null,
				$version,
				true
			);
		}
	
		// enqueue the script
		if ( ! wp_style_is( 'greyd-query-postslider-script', 'enqueued') ) {
			wp_enqueue_script( 'greyd-query-postslider-script' );
		}

		// register the live filter script
		if ( ! wp_style_is( 'greyd-query-livefilter-script', 'registered') ) {
			wp_register_script(
				'greyd-query-livefilter-script',
				$this->config->assets_url.'assets/js/live-filter.js',
				null,
				$version,
				true
			);
			wp_localize_script(
				'greyd-query-livefilter-script',
				'WP_REST_API',
				array(
					'root' => esc_url_raw( str_replace( 'wp-json', '?rest_route=', rest_url() ) ),
					'paths' => array(
						'livequery' => 'greyd/v1/livequery/'
					),
					'lang' => \Greyd\Helper::get_language_code()
				)
			);
		}

		// register the main style
		wp_register_style(
			'greyd-post-slider-style',
			$this->config->assets_url.'assets/css/style.css',
			array( ),
			$version
		);
		wp_enqueue_style('greyd-post-slider-style');
		
		// todo: move to Query Feature
		wp_register_style(
			'greyd-query-frontend-style',
			$this->config->assets_url.'assets/css/blocks-query.css',
			array( ),
			$this->config->plugin_version
		);
		wp_enqueue_style('greyd-query-frontend-style');

		// dequeue deprecated style
		wp_dequeue_style( 'greyd-query-style' );
		// wp_dequeue_style( 'greyd-query-frontend-style' );
		
	}

	/**
	 * Enqueue block styles.
	 * @action enqueue_block_assets
	 */
	public function register_block_editor_styles() {

		if ( ! is_admin() ) return;

		/**
		 * load styles only on editor pages.
		 * can be removed when proper action 'enqueue_block_assets' can be used.
		 */
		$screen = get_current_screen();
		if (
			$screen->base != 'site-editor' &&
			method_exists($screen, 'is_block_editor') &&
			!$screen->is_block_editor()
		) {
			// debug("not editor");
			return;
		}

		// add preview style
		add_editor_style( $this->config->assets_url.'assets/css/editor-blocks.css' );

		// todo: move to Query Feature
		if ( defined( 'GREYD_VERSION' ) && version_compare( GREYD_VERSION, '1.6.9', '>' ) ) {
			wp_register_style(
				'greyd-query-frontend-style',
				$this->config->assets_url.'assets/css/blocks-query.css',
				array( ),
				$this->config->plugin_version
			);
			wp_enqueue_style( 'greyd-query-frontend-style' );
		}

	}
	
	/**
	 * Register and enqueue all the scripts for the editor.
	 * @action enqueue_block_editor_assets
	 */
	public function register_block_editor_scripts() {

		// add editor script
		wp_register_script(
			'greyd-query-editor-script',
			$this->config->assets_url.'assets/js/editor.js',
			array( 'greyd-tools', 'wp-blocks', 'wp-element', 'wp-block-editor', 'wp-components', 'wp-i18n', 'lodash', 'wp-core-data', 'wp-edit-post' ),
			$this->config->plugin_version
		);
		wp_enqueue_script( 'greyd-query-editor-script' );

		// add script translations
		if ( function_exists('wp_set_script_translations') ) {
			wp_set_script_translations( 'greyd-query-editor-script', 'greyd_hub', $this->config->plugin_path.'/languages' );
		}
	}
	
	
	/**
	 * Hook Greyd block rendering.
	 * 
	 * @filter 'greyd_blocks_render_block'
	 * 
	 * @param array $content
	 *      @property string block_content     block content about to be appended.
	 *      @property array  html_atts         html wrapper attributes
	 *      @property string style             css styles
	 * @param array  $block             full block, including name and attributes.
	 * 
	 * @return array $rendered
	 *      @property string block_content    altered Block Content
	 *      @property string html_atts        altered html wrapper attributes
	 *      @property string style            altered css styles
	 */
	public static function render_block($content, $block) {
		// debug("render list");

		$block_content = $content['block_content'];
		$html_atts     = $content['html_atts'];
		$style         = $content['style'];

		// query block (post overview)
		if ( $block['blockName'] === 'core/query' ) {
			// debug($block['blockName']);
			// debug($block);
			// debug(htmlspecialchars($block_content));
			// debug($block_content);

			// attributes (query, queryId, anchor, etc) get passed to 'core/post-template' child elements
		}
		if ( $block['blockName'] === 'core/post-template' ) {

			if ( class_exists( '\Greyd\Query\Query_Block' ) ) {
				$block_content = ( new \Greyd\Query\Query_Block( $block, $block_content ) )->render();
			}
		}
		if ( $block['blockName'] === 'greyd/post-table' ) {

			if ( class_exists( '\Greyd\Query\Post_Table' ) ) {
				$block_content = \Greyd\Query\Post_Table::render( $block, $block_content );
			}
		}
		if ( strpos( $block['blockName'], 'pagination' ) > -1 ) {
			// debug($block['blockName']);
			// debug($block);
			// debug(htmlspecialchars($block_content));

			// debug($block);
			$table = isset( $block['attrs']['query']['displayLayout']['type'] ) && $block['attrs']['query']['displayLayout']['type'] == 'table';
			if ( ! $table && ! ( isset( $block['attrs']['query']['query']['inherit'] ) && $block['attrs']['query']['query']['inherit'] ) ) {
				// replace href links with events
				preg_match_all( '/(href=")([^"]*)/', $block_content, $matches );
				// debug($matches);
				if ( isset( $matches[0] ) && count( $matches[0] ) > 0 ) {
					for ( $i = 0; $i < count( $matches[0] ); $i++ ) {
						// debug($matches[2][$i]);
						if ($block['blockName'] === 'core/query-pagination-previous')
							$block_content = str_replace('href="'.$matches[2][$i].'"', 'onclick="greyd.query.slider.triggerPrevious(this)"', $block_content);
						else if ($block['blockName'] === 'core/query-pagination-next')
							$block_content = str_replace('href="'.$matches[2][$i].'"', 'onclick="greyd.query.slider.triggerNext(this)"', $block_content);
						else {
							$url = parse_url(str_replace('&#038;', '&', $matches[2][$i]));
							parse_str($url['query'], $params);
							// debug($params);
							$index = '1';
							foreach ( $params as $key => $val ) {
								if ( strpos( $key, 'query-' ) === 0 && strpos( $key, '-page' ) > 0 ) {
									$index = $val;
								}
							}
							$block_content = str_replace('href="'.$matches[2][$i].'"', 'onclick="greyd.query.slider.triggerIndex(this, '.$index.')"', $block_content);
						}
					}
				}
				if ($block['blockName'] === 'core/query-pagination-numbers') {
					$block_content = str_replace('<span', '<a onclick="greyd.query.slider.triggerIndex(this, 1)"', $block_content);
					$block_content = str_replace('</span', '</a', $block_content);
				}
				// debug(htmlspecialchars($block_content));

			}
		}
		// debug($block_content);

		return array(
			'block_content' => $block_content,
			'html_atts' => $html_atts,
			'style' => $style
		);

	}

}