<?php
/**
 * Deployment item related functions.
 *
 * @package EaLab\WP_Deployer
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Requires.
 */
require_once __DIR__ . '/component-based-object.php';

use EaLab\WP_Deployer\vendor\Ealab\Deployer\Exception\WpDeployException;
use EaLab\WP_Deployer\vendor\Ealab\Deployer\Utility\FileManager;

/**
 * Gets the available items for import.
 *
 * @param string     $subdirectory The subdirectory of the bundle.
 * @param array|null $item_full_uuids The full UUIDs of the items to import.
 *   If null, all the available items will be returned.
 *
 * @return array<string,array> The available items for import, keyed by full UUID.
 *
 * @throws WpDeployException Could not get the available items for import.
 */
function deploy_sync_content__get_items_for_import( string $subdirectory, ?array $item_full_uuids = null ): array {
	if ( empty( $subdirectory ) ) {
		return array();
	}

	$file_manager = deploy_sync_content__get_root_cbo( FileManager::class );

	// Get all the item UUIDs to import.
	$item_full_uuids = $item_full_uuids ?? $file_manager->getAllAvailableUuidsForImport( $subdirectory );

	// Load the data of the items to import.
	return $file_manager->loadDeploymentItemsData( $subdirectory, $item_full_uuids );
}

/**
 * Gets the UUID from deployment item.
 *
 * @param array $item The deployment item.
 * @param bool  $as_full_uuid Whether to return the full UUID or not.
 *
 * @return string The UUID. May return an empty string if the data is invalid.
 */
function deploy_sync_content__get_uuid_from_deployment_item( array $item, bool $as_full_uuid = true ): string {
	$uuid = $item['uuid'] ?? '';

	if ( empty( $uuid ) ) {
		return '';
	}

	if ( empty( $as_full_uuid ) ) {
		return esc_html( $uuid );
	}

	$tracker = $item['tracker'] ?? '';

	if ( empty( $tracker ) ) {
		return '';
	}

	return esc_html( implode( '.', array( $tracker, $uuid ) ) );
}
