<?php

namespace iThemesSecurity\Import_Export\Import;

use iThemesSecurity\Contracts\Import_Export_Source;
use iThemesSecurity\Import_Export\Export\Export;
use iThemesSecurity\Lib\Result;

final class Importer {

	/** @var array */
	private $export_schema;

	/** @var Import_Export_Source[] */
	private $sources;

	public function __construct( array $export_schema, array $sources ) {
		$this->export_schema = $export_schema;
		$this->sources       = $sources;
	}

	public function import( Export $export, Import_Context $context ): Result {
		if ( ! $this->export_schema ) {
			return Result::error( new \WP_Error(
				'itsec.import-export.missing-schema',
				__( 'Cannot validate export as validation schema is missing.', 'it-l10n-ithemes-security-pro' ),
				[ 'status' => \WP_Http::INTERNAL_SERVER_ERROR ]
			) );
		}

		$valid = $export->validate_against( $this->export_schema );

		if ( is_wp_error( $valid ) ) {
			return Result::error( $valid );
		}

		if ( $export->get_build() > \ITSEC_Core::get_plugin_build() ) {
			return Result::error( new \WP_Error(
				'itsec.import-export.newer-build',
				__( 'Cannot complete import as the export was generated by a newer version of iThemes Security.', 'it-l10n-ithemes-security-pro' ),
				[ 'status' => \WP_Http::BAD_REQUEST ]
			) );
		}

		$export  = $this->transform( $export, $context );
		$results = [];

		foreach ( $this->sources as $source ) {
			if (
				$export->has_data( $source->get_export_slug() ) &&
				$context->is_source_included( $source->get_export_slug() )
			) {
				$results[] = $source->import( $export, $context );
			}
		}

		return Result::combine( ...$results );
	}

	public function transform( Export $export, Import_Context $context ): Export {
		foreach ( $this->sources as $source ) {
			if ( ! $export->has_data( $source->get_export_slug() ) ) {
				continue;
			}

			foreach ( $source->get_transformations() as $transformation ) {
				$export = $transformation->transform( $export, $context );
			}
		}

		return $export;
	}
}
