<?php
namespace TotalTheme;

use TotalTheme\Theme_Icons;

defined( 'ABSPATH' ) || exit;

/**
 * Class used to insert links in the head for preloading assets.
 *
 * @package TotalTheme
 * @version 5.5
 */
class Preload_Assets {

	/**
	 * Return array of links.
	 */
	public static function get_links() {
		$links = array();

		// Theme Icon woff2 file.
		if ( 'font' === Theme_Icons::get_format() ) {
			$links[] = array(
				'href'        => wpex_asset_url( 'lib/ticons/fonts/ticons.woff2' ),
				'type'        => 'font/woff2',
				'as'          => 'font',
				'crossorigin' => true,
				'condition'   => wp_style_is( 'ticons' ),
			);
		}

		/**
		 * Filters the links to preload.
		 *
		 * @param array $links
		 */
		$links = (array) apply_filters( 'wpex_preload_links', $links );

		return $links;
	}

	/**
	 * Add links to wp_head
	 */
	public static function add_links() {
		if ( defined( 'IFRAME_REQUEST' ) && IFRAME_REQUEST ) {
			return; // prevents preloading in iFrames where it's not needed (like widgets block editor).
		}

		$links = self::get_links();

		if ( ! $links ) {
			return;
		}

		foreach ( $links as $link => $atts ) {
			if ( array_key_exists( 'condition', $atts ) && false === $atts['condition'] ) {
				continue;
			}
			echo self::render_link( $atts );
		}
	}

	/**
	 * Renders a single link.
	 *
	 * @since 5.4
	 */
	private static function render_link( $atts = array() ) {
		$link = '';
		$link .= '<link rel="preload" href="' . esc_url( $atts['href'] ) . '"';
			if ( isset( $atts['type'] ) ) {
				$link .= ' type="' . esc_attr( $atts['type'] ) . '"';
			}
			if ( isset( $atts['as'] ) ) {
				$link .= ' as="' . esc_attr( $atts['as'] ) . '"';
			}
			if ( isset( $atts['media'] ) ) {
				$link .= ' media="' . esc_attr( $atts['media'] ) . '"';
			}
			if ( isset( $atts['crossorigin'] ) ) {
				$link .= ' crossorigin';
			}
		$link .= '>';
		return $link;
	}

}