<?php

namespace Wb4Wp\Managers;

/**
 * Class Performance_Manager
 * @package Wb4Wp\Managers
 */
class Performance_Manager {

	const DEFERRED_SCRIPT_HANDLES = array();

	const DEFERRED_STYLE_HANDLES = array(
		'load-style-2',
		'font-awesome',
	);

	public static function initialize() {
		add_filter( 'script_loader_tag', array( self::class, 'get_script_tag' ), 10, 3 );
		add_filter( 'style_loader_tag', array( self::class, 'get_style_tag' ), 10, 4 );
	}

	public static function get_script_tag( $tag, $handle, $src ) {
		$is_deferred_script = in_array( $handle, self::DEFERRED_SCRIPT_HANDLES, true );
		if ( ! self::is_loading_editor() || ! $is_deferred_script ) {
			return $tag;
		}

		// phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedScript
		return "<script defer src='" . esc_url( $src ) . "'></script>";
	}

	public static function get_style_tag( $tag, $handle, $href, $media ) {
		$is_deferred_style = in_array( $handle, self::DEFERRED_STYLE_HANDLES, true );
		if ( ! self::is_loading_editor() || ! $is_deferred_style ) {
			return $tag;
		}

		// phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet
		return "<link rel='preload' href='$href' as='style' media='$media' onload='this.onload = null; this.rel=`stylesheet`'>";
	}

	private static function is_loading_editor() {
		global $pagenow;
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$page_query_parameter = ! empty( $_GET['page'] ) ? $_GET['page'] : null;

		return 'admin.php' === $pagenow && 'wb4wp-editor' === $page_query_parameter;
	}

}
