<?php

declare(strict_types=1);

namespace Drupal\languagewire_translation_provider\Adapter\PreviewSite\CleanupAction;

use Drupal\languagewire_translation_provider\Content\HtmlPreview\HtmlPreviewUrlProcessor;
use Drupal\languagewire_translation_provider\Content\HtmlPreview\Result\HtmlPreviewResult;

/**
 * Preview site cleanup action that fixes the URLs in the HTML files.
 */
final class PreviewSiteUrlFixer extends PreviewSiteCleanupActionBase {

  /**
   * Url processor.
   *
   * @var \Drupal\languagewire_translation_provider\Content\HtmlPreview\HtmlPreviewUrlProcessor
   */
  private HtmlPreviewUrlProcessor $urlProcessor;

  /**
   * Constructs a new PreviewSiteUrlFixer object.
   *
   * @param \Drupal\languagewire_translation_provider\Content\HtmlPreview\HtmlPreviewUrlProcessor $urlProcessor
   *   Url processor.
   */
  public function __construct(HtmlPreviewUrlProcessor $urlProcessor) {
    $this->urlProcessor = $urlProcessor;
  }

  /**
   * {@inheritdoc}
   */
  public function cleanUpResult(HtmlPreviewResult $htmlPreviewResult): HtmlPreviewResult {
    $htmlFiles = $this->findFiles(
          $htmlPreviewResult,
          function (\SplFileInfo $file): bool {
              return $this->isHtmlFile($file);
          }
      );

    foreach ($htmlFiles as $file) {
      $contents = file_get_contents($file->getRealPath());

      if ($contents !== FALSE) {
        $updatedContent = $this->urlProcessor->setRelativeUrls($contents);
        file_put_contents($file->getRealPath(), $updatedContent);
      }
    }

    return $htmlPreviewResult;
  }

  /**
   * Checks if the file is an HTML file.
   */
  private function isHtmlFile(\SplFileInfo $file): bool {
    return str_contains($file->getFilename(), '.html');
  }

}
