<?php
/**
 * Manager for TrackDateInitializerBase classes.
 *
 * @package Ealab\Deployer
 */

namespace Ealab\Deployer\Tracking\ItemTracker\TrackDateInitializer;

use Dakwamine\Component\ComponentBasedObject;

/**
 * Manager for TrackDateInitializerBase classes.
 */
class TrackDateInitializerManager extends ComponentBasedObject {
	/**
	 * Track date initializer class names.
	 *
	 * Use the getInitializerClassNames() method instead of this property.
	 *
	 * @var string[]|null
	 */
	private ?array $track_date_initializers_class_names = null;

	/**
	 * The initializer class name by ID.
	 *
	 * @param string|null $id The ID of the initializer. Leave empty to get the default initializer.
	 *
	 * @return string Class name.
	 */
	public function getInitializerClassNameById( ?string $id = null ): string {
		if ( empty( $id ) ) {
			// Return the default class.
			return TrackDateInitializerBase::class;
		}

		return $this->getInitializerClassNames()[ $id ] ?? TrackDateInitializerBase::class;
	}

	/**
	 * Gets the list of class names.
	 *
	 * @return array The class names.
	 */
	private function getInitializerClassNames(): array {
		if ( null === $this->track_date_initializers_class_names ) {
			$this->track_date_initializers_class_names = apply_filters( 'deploy_sync_content__get_track_date_initializers', array() );
		}

		return $this->track_date_initializers_class_names;
	}

	/**
	 * Called on plugin init.
	 */
	public static function onPluginInit(): void {
		add_filter(
			'deploy_sync_content__get_track_date_initializers',
			static function ( array $data = array() ): array {
				/** @var TrackDateInitializerBase[] $initializers */
				$initializers = array(
					TrackDateInitializerBase::class,
					PostsTrackDateInitializer::class,
					PostmetaTrackDateInitializer::class,
				);

				foreach ( $initializers as $initializer ) {
					$data[ $initializer::getId() ] = $initializer;
				}

				return $data;
			},
			10,
			1
		);
	}
}
