<?php
/**
 * Handles cron syncers.
 *
 * @package northmill-online-shared
 */

declare(strict_types=1);

namespace Northmill_Online_Shared\Abstracts\Hub_API\Sync\Ajax;

use Northmill_Online_Shared\Abstracts\Hub_API\Sync\Abstract_Syncer;
use Northmill_Online_Shared\Abstracts\Hub_API\Sync\Ajax\Models\Sync_Request_Model;

defined( 'ABSPATH' ) || exit;

/**
 * Class Cron_Syncers
 */
class Ajax_Syncers {

	/**
	 * All constructed ajax syncers.
	 *
	 * @var Sync_Request_Model[]
	 */
	private static array $ajax_syncers = array();

	/**
	 * Add a new syncer.
	 *
	 * @param string          $key               Syncer key.
	 *                                           This key is used to get the syncer instance.
	 * @param Abstract_Syncer $syncer            Syncer instance.
	 * @param string          $ajax_action       Ajax action to call the syncer.
	 * @param int             $priority          Priority of the syncer.
	 *
	 * @return Sync_Request_Model Sync request model.
	 */
	public static function add_syncer(
		string $key,
		Abstract_Syncer $syncer,
		string $ajax_action,
		int $priority = 10
	): Sync_Request_Model {
		self::$ajax_syncers[ $key ] = new Sync_Request_Model(
			$ajax_action,
			$syncer,
			$priority
		);

		return self::$ajax_syncers[ $key ];
	}

	/**
	 * Get ajax syncer by name.
	 *
	 * @param string $name Cron syncer name.
	 *
	 * @return Sync_Request_Model|null
	 */
	public static function get_syncer( string $name ): ?Sync_Request_Model {
		return self::$ajax_syncers[ $name ] ?? null;
	}

	/**
	 * Get all cron syncers.
	 *
	 * @param bool $ordered If the syncers should be ordered by priority.
	 *
	 * @return Sync_Request_Model[]
	 */
	public static function get_all( bool $ordered = false ): array {
		if ( ! $ordered ) {
			return self::$ajax_syncers;
		}

		$ajax_syncers = self::$ajax_syncers;

		uasort(
			$ajax_syncers,
			function ( $a, $b ) {
				return $a->get_priority() <=> $b->get_priority();
			}
		);

		return array_values( $ajax_syncers );
	}
}
