<?php
namespace ShortPixel\Model\Converter;

if ( ! defined( 'ABSPATH' ) ) {
 exit; // Exit if accessed directly.
}

use ShortPixel\ShortPixelLogger\ShortPixelLogger as Log;
use ShortPixel\Model\Queue\QueueItem as QueueItem;
use ShortPixel\Helper\UtilHelper as UtilHelper;

/**
 * Converter for BMP images using the WordPress-native image pipeline.
 *
 * Handles conversion of BMP files by leveraging existing media library
 * infrastructure, creating a backup before processing and updating
 * WordPress metadata on completion.
 *
 * @package ShortPixel\Model\Converter
 */
class BMPConverter extends MediaLibraryConverter
{

	/** @var array File extensions this converter handles. */
  const CONVERTABLE_EXTENSIONS = array( 'bmp');


	/**
	 * Determines whether the current image can be converted by this converter.
	 *
	 * @return bool True for BMP images, false for all others.
	 */
  public function isConvertable()
  {
    $extension = $this->imageModel->getExtension();

    // If extension is in list of allowed Api Converts.
    if (in_array($extension, static::CONVERTABLE_EXTENSIONS) && $extension !== 'png')
    {
       return true;
    }
    return false;
  }

	/**
	 * Prepares the queue item for BMP conversion by triggering a conversion backup.
	 *
	 * @param QueueItem $item The queue item to prepare.
	 * @param array     $args Additional arguments; 'debug_active' skips the backup step.
	 * @return QueueItem The (unmodified) queue item.
	 */
  public function filterQueue(QueueItem $item, $args = array())
  {
    // Create backup and such.
    $conversion_args = array(
        'backup_thumbnails' => false, // no need for this. either they should be optimized, or generated after the run
    );

    if (false === $args['debug_active'])
    {
        $this->imageModel->conversionPrepare($conversion_args);
    }
    return $item;
  }

	/**
	 * Handles the optimized file returned by the optimizer after a BMP conversion.
	 *
	 * Copies the returned file to the replacement path, updates WordPress metadata,
	 * runs the URL replacer, and marks the conversion as successful.
	 *
	 * @param array $optimizeData Data returned by the optimizer, containing 'files' and 'data' keys.
	 * @return array The original $optimizeData array (pass-through).
	 */
  public function handleConvertedFilter($optimizeData)
  {
    $this->setupReplacer();
    $fs = \wpSPIO()->filesystem();

    $extension = $this->imageModel->getExtension();
    $replacementBase = $this->imageModel->getMeta()->convertMeta()->getReplacementImageBase();
    if (false === $replacementBase)
    {
      $replacementPath = $this->getReplacementPath();
      $replacementFile = $fs->getFile($replacementPath);
    }
    else {
      $replacementPath = $replacementBase . '.jpg';
      $replacementFile = $fs->getFile($this->imageModel->getFileDir() . $replacementPath);
    }

    if (isset($optimizeData['files']) && isset($optimizeData['data']))
    {
       $files = $optimizeData['files'];
       $data = $optimizeData['data'];
    }
    else {
      Log::addError('Something went wrong with handleOptimized', $optimizeData);
      return $optimizeData;
    }

    $mainImageKey = $this->imageModel->get('mainImageKey');
    $mainFile = (isset($files) && isset($files[$mainImageKey])) ? $files[$mainImageKey] : false;

    if (false === $mainFile)
    {
      // Error, but can also be multiple other thumbs returning.
       Log::addDebug('MainFile not set (so far?) ');
       return $optimizeData;
    }

    if (! isset($mainFile['image']) || ! isset($mainFile['image']['file']))
    {
      Log::addDebug('MainFile not set (so far?) ');
      return $optimizeData;
    }

    $tempFile = $fs->getFile($mainFile['image']['file']);
    $res = $tempFile->copy($replacementFile);



// @ todo  If the thumbnails generated by WP are of the BMP format, generate_metadata should be tryue and skip_thumbnails should be false. Otherwise it should be reversed and thumbnails left alone.
    $this->setTarget($replacementFile);
    $this->updateMetaData([
        'generate_metadata' => false,
        'success' => true
    ]);

    $result = $this->replacer->replace();
    $res = $this->imageModel->conversionSuccess(['skip_thumbnails' => true, 'omit_backup' => true]);

    return $optimizeData;


  } // handleConverterFilter


	/**
	 * Returns a fixed checksum indicating whether a conversion has been attempted.
	 *
	 * @return int Always 1.
	 */
  public function getCheckSum()
  {
     return 1; // done or not.
  }

	/**
	 * Conversion entry point. Not implemented for BMP; conversion happens via the API pipeline.
	 *
	 * @param array $args Unused arguments.
	 * @return void
	 */
  public function convert($args = [])
  {

  }

	/**
	 * Restores the image to its original BMP format by updating WordPress metadata
	 * to point back to the .bmp file and running the URL replacer.
	 *
	 * @return void
	 */
  public function restore()
  {
    $params = array(
      'restore' => true,
    );
    $fs = \wpSPIO()->filesystem();

    $this->setupReplacer();

    $oldFileName = $this->imageModel->getFileName(); // Old File Name, Still .jpg
    $newFileName =  $this->imageModel->getFileBase() . '.bmp';

    if ($this->imageModel->isScaled())
    {
       $oldFileName = $this->imageModel->getOriginalFile()->getFileName();
       $newFileName = $this->imageModel->getOriginalFile()->getFileBase() . '.bmp';
    }

    $fsNewFile = $fs->getFile($this->imageModel->getFileDir() . $newFileName);

    $this->newFile = $fsNewFile;
    $this->setTarget($fsNewFile);

    $this->updateMetaData($params);
    $result = $this->replacer->replace();

    $fs->flushImageCache();


  }
}
