<?php
/**
 * Post GUID item value handler.
 *
 * @package Ealab\Deployer
 */

namespace Ealab\Deployer\Tracking\ItemValueHandler;

use Ealab\Deployer\Tracking\ItemValueHandler\ValueProcessor\AttachmentProcessor;
use Ealab\Deployer\Tracking\ItemValueHandler\ValueProcessor\ClearElementorCacheOnImportProcessor;

/**
 * Post GUID item value handler.
 */
class PostGuidItemValueHandler extends ItemValueHandlerBase {
	/**
	 * {@inheritdoc}
	 */
	public static function getHandlerBaseId(): string {
		return 'post_guid';
	}

	/**
	 * {@inheritDoc}
	 */
	public static function getLabel(): string {
		return _dpgettext( 'deployer-core', 'item value handler', 'Post GUID' );
	}

	/**
	 * {@inheritDoc}
	 */
	protected function processValue( $value, int $operation, ?callable $progress_callback = null ) {
		$holder_values = $this->getHolder()->getRawDataFields();

		if ( empty( $holder_values['post_type'] ) ) {
			// Nothing special can be done here.
			return parent::processValue( $value, $operation, $progress_callback );
		}

		switch ( $holder_values['post_type'] ) {
			case 'attachment':
				if ( empty( $this->getComponentByClassName( AttachmentProcessor::class ) ) ) {
					// Prepend the processor list with the attachment processor.
					$this->value_processor_manager->prependProcessorInstanceTo(
						array(
							'id' => 'attachment',
						),
						$this
					);
				}

				break;

			case 'elementor_library':
			case 'page':
			case 'post':
				if ( class_exists( 'Elementor\Plugin' ) && empty( $this->getComponentByClassName( ClearElementorCacheOnImportProcessor::class ) ) ) {
					// This is a little hack for elementor:
					// When Elementor is installed, on post, elementor_library or page import,
					// we order a cache clear after the import.
					// TODO: Later, it would be better to have this configurable,
					// because this configuration is specific to a third party plugin (Elementor).
					$this->value_processor_manager->prependProcessorInstanceTo(
						array(
							'id' => 'clear_elementor_cache_on_import',
						),
						$this
					);
				}

				break;

			default:
				// This is not an attachment, nothing can be done here.
				break;
		}

		return parent::processValue( $value, $operation, $progress_callback );
	}
}
