<?php
/**
 * Registry of competitor import adapters.
 *
 * @package StoreSheet
 */

declare( strict_types=1 );

namespace StoreSheet\Importer;

defined( 'ABSPATH' ) || exit;

use StoreSheet\Importer\Adapters\FlexOrderAdapter;
use StoreSheet\Importer\Adapters\FlexStockAdapter;
use StoreSheet\Importer\Adapters\GSheetConnectorAdapter;
use StoreSheet\Importer\Adapters\GenericAdapter;
use StoreSheet\Importer\Adapters\ProductSyncMasterAdapter;
use StoreSheet\Importer\Adapters\SpreadsheetSyncAdapter;
use StoreSheet\Importer\Adapters\WpgsiAdapter;
use StoreSheet\Importer\Adapters\WpSyncSheetsAdapter;

final class AdapterRegistry {

	/** @var SourceAdapter[] */
	private array $adapters;

	public function __construct() {
		$defaults = array(
			new GSheetConnectorAdapter(),
			new WpSyncSheetsAdapter(),
			new FlexOrderAdapter(),
			new FlexStockAdapter(),
			new SpreadsheetSyncAdapter(),
			new ProductSyncMasterAdapter(),
			new WpgsiAdapter(),
			new GenericAdapter(),
		);

		/**
		 * Register competitor import adapters. Pro and third parties append here.
		 *
		 * @since 1.1.0
		 * @param SourceAdapter[] $defaults
		 */
		$adapters = apply_filters( 'storesheet_import_adapters', $defaults );

		$this->adapters = array_values(
			array_filter(
				(array) $adapters,
				static function ( $a ) {
					return $a instanceof SourceAdapter;
				}
			)
		);
	}

	/** @return SourceAdapter[] */
	public function all(): array {
		return $this->adapters;
	}

	/** @return SourceAdapter[] Present competitors only. */
	public function detected(): array {
		return array_values(
			array_filter(
				$this->adapters,
				static function ( SourceAdapter $a ) {
					return $a->is_present();
				}
			)
		);
	}

	public function get( string $id ): ?SourceAdapter {
		foreach ( $this->adapters as $a ) {
			if ( $a->id() === $id ) {
				return $a;
			}
		}
		return null;
	}
}
