<?php

namespace Brandy\BlockSettings\ButtonSize;

use Brandy\Traits\SingletonTrait;
use Brandy\Interfaces\ExternalBlockSettingsInterface;

class Caller implements ExternalBlockSettingsInterface {
	use SingletonTrait;

	private $enqueued_styles = false;

	protected function __construct() {
		add_filter( 'block_type_metadata_settings', array( $this, 'declare_attribute' ), 10 );
		add_action( 'enqueue_block_assets', array( $this, 'enqueue_editor_styles' ) );
		add_action( 'enqueue_block_editor_assets', array( $this, 'enqueue_settings_scripts' ) );
		add_filter( 'render_block_core/button', array( $this, 'apply_button_size_to_blocks' ), 10, 2 );
		add_filter( 'render_block_brandy/button', array( $this, 'apply_button_size_to_blocks' ), 10, 2 );
	}

	private function is_button_block( $name ) {
		return in_array( $name, array( 'core/button', 'brandy/button' ) );
	}

	public function declare_attribute( $settings ) {

		if ( empty( $settings['name'] ) ) {
			return $settings;
		}

		if ( ! $this->is_button_block( $settings['name'] ) ) {
			return $settings;
		}

		if ( ! empty( $settings['attributes'] ) ) {
			$settings['attributes']['size'] = array(
				'type'    => 'string',
				'default' => '',
			);
		}
		return $settings;
	}

	public function enqueue_settings_scripts() {
		wp_enqueue_script( 'brandy/button-size', BRANDY_TEMPLATE_URL . '/inc/BlockSettings/ButtonSize/script.js', array( 'wp-edit-post' ), BRANDY_SCRIPT_VERSION, true );
	}

	public function enqueue_editor_styles() {
		$this->maybe_enqueue_frontend_styles( true );
	}

	public function maybe_enqueue_frontend_styles( $admin_enqueue = false ) {

		if ( $this->enqueued_styles ) {
			return;
		}
		if ( $admin_enqueue && ! is_admin() ) {
			return;
		}

		if ( ! $admin_enqueue && is_admin() ) {
			return;
		}

		$this->enqueued_styles = true;

		wp_enqueue_style( 'brandy/button-size', BRANDY_TEMPLATE_URL . '/inc/BlockSettings/ButtonSize/style.css', array(), BRANDY_SCRIPT_VERSION );
	}

	public function apply_button_size_to_blocks( $html, $block ) {
		if ( ! empty( $block['attrs']['size'] ) ) {
			$this->maybe_enqueue_frontend_styles();
		}
		return $html;
	}

}

Caller::get_instance();
