<?php
/**
 * Converts a GUID (URL) into a JSON object with the represented encoded file and relative path.
 *
 * @package Ealab\Deployer
 */

namespace Ealab\Deployer\Tracking\ItemValueHandler\ValueProcessor;

use Ealab\Deployer\Exception\IgnoredTransmutationException;
use Ealab\Deployer\Tracking\ItemValueHandler\ItemValueHandlerBase;
use Ealab\Deployer\Tracking\ItemValueHandler\ValueProcessor\TransmutationHandler\FileTransmutationHandler;

/**
 * Converts a GUID (URL) into a JSON object with the represented encoded file and relative path.
 */
class AttachmentProcessor extends ValueProcessorBase {
	/**
	 * {@inheritDoc}
	 */
	public static function getId(): string {
		return 'attachment';
	}

	/**
	 * {@inheritDoc}
	 */
	public static function getLabel(): string {
		// i18n: This processor finds the file (image, attachment) represented by the value (URL/GUID)
		// and includes it in the export bundle.
		return _dpgettext( 'deployer-core', 'processor label', 'Convert GUID into its represented file' );
	}

	/**
	 * {@inheritDoc}
	 */
	public function process( $value, int $operation, ?callable $progress_callback = null ) {
		if ( ! is_string( $value ) ) {
			// We only process strings here.
			return $value;
		}

		switch ( $operation ) {
			case ItemValueHandlerBase::OPERATION__EXPORT:
				// This is also the operation to use when we want to compare the values.
				try {
					return FileTransmutationHandler::packAttachmentFile( $value );
				} catch ( IgnoredTransmutationException $e ) {
					// The file is not available, we ignore it.
					return $value;
				}

			case ItemValueHandlerBase::OPERATION__IMPORT__PRESAVE:
				// Do not attempt to write the file here.
				return $value;

			case ItemValueHandlerBase::OPERATION__IMPORT__FINALIZE:
				try {
					// Write the file. The operation may fail, but it's not a big deal.
					return FileTransmutationHandler::unpackAttachmentFile( $value );
				} catch ( IgnoredTransmutationException $e ) {
					return $value;
				}
		}

		return $value;
	}
}
