<?php

namespace EaLab\WP_Deployer\includes\blueprint;

use EaLab\WP_Deployer\vendor\Symfony\Component\Yaml\Yaml;
use Throwable;

class BlueprintLoader {
	static public function copyStateFromRequest( \WP_REST_Request $request, array &$blueprint = array() ) {
		$request_state = static::getRequestState( $request );

		if ( ! isset( $request ) ) {
			// No state.
			return;
		}

		$blueprint['data']['__state'] = $request_state;
	}

	/**
	 * Gets the base structure blueprint.
	 *
	 * @param string              $filename The filename of the blueprint to load. Supports only YAML for now.
	 * @param array<string,mixed> $options Options to pass:
	 *     - "reset_data", string: Set to TRUE to reset the data. Defaults to TRUE.
	 *     - "set_random_build_id", string: Set to TRUE to set an ID that will force html-biulder to update.
	 *       Defaults to TRUE.
	 *
	 * @return array The base structure parsed as array.
	 *
	 * @throws Throwable Could not parse the file.
	 */
	static public function getBaseBlueprint( string $filename, array $options = array() ): array {
		$yaml = file_get_contents( $filename );

		$parsed = Yaml::parse( $yaml );

		if ( $options['reset_data'] ?? true ) {
			// Remove the eventual test data.
			$parsed['data'] = [];
		}

		if ( $options['set_random_build_id'] ?? true ) {
			$parsed['data']['__build_id'] = microtime(true);
		}

		return $parsed;
	}

	static public function getRequestState( \WP_REST_Request $request ): ?array {
		$maybe_body = $request->get_body();

		if ( empty( $maybe_body ) ) {
			return null;
		}

		$decoded = json_decode( $maybe_body, true );

		return $decoded['data']['__state'] ?? null;
	}
}
