<?php
/**
 * KKART Queue
 *
 * @version 3.5.0
 * @package Kkart\Interface
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

/**
 * KKART Queue
 *
 * Singleton for managing the KKART queue instance.
 *
 * @version 3.5.0
 */
class KKART_Queue {

	/**
	 * The single instance of the queue.
	 *
	 * @var KKART_Queue_Interface|null
	 */
	protected static $instance = null;

	/**
	 * The default queue class to initialize
	 *
	 * @var string
	 */
	protected static $default_cass = 'KKART_Action_Queue';

	/**
	 * Single instance of KKART_Queue_Interface
	 *
	 * @return KKART_Queue_Interface
	 */
	final public static function instance() {

		if ( is_null( self::$instance ) ) {
			$class          = self::get_class();
			self::$instance = new $class();
			self::$instance = self::validate_instance( self::$instance );
		}
		return self::$instance;
	}

	/**
	 * Get class to instantiate
	 *
	 * And make sure 3rd party code has the chance to attach a custom queue class.
	 *
	 * @return string
	 */
	protected static function get_class() {
		if ( ! did_action( 'plugins_loaded' ) ) {
			kkart_doing_it_wrong( __FUNCTION__, __( 'This function should not be called before plugins_loaded.', 'kkart' ), '3.5.0' );
		}

		return apply_filters( 'kkart_queue_class', self::$default_cass );
	}

	/**
	 * Enforce a KKART_Queue_Interface
	 *
	 * @param KKART_Queue_Interface $instance Instance class.
	 * @return KKART_Queue_Interface
	 */
	protected static function validate_instance( $instance ) {
		if ( false === ( $instance instanceof KKART_Queue_Interface ) ) {
			$default_class = self::$default_cass;
			/* translators: %s: Default class name */
			kkart_doing_it_wrong( __FUNCTION__, sprintf( __( 'The class attached to the "kkart_queue_class" does not implement the KKART_Queue_Interface interface. The default %s class will be used instead.', 'kkart' ), $default_class ), '3.5.0' );
			$instance = new $default_class();
		}

		return $instance;
	}
}
