<?php

declare(strict_types=1);

namespace Drupal\languagewire_translation_provider\Adapter\PreviewSite\CleanupAction;

use Drupal\languagewire_translation_provider\Content\HtmlPreview\Result\HtmlPreviewResult;
use function rename;

/**
 * Preview site index file mover.
 *
 * PreviewSiteIndexFileMover moves the generated index.html file
 * to the root folder of the static copy of the page.
 *
 * The reason for this is that LanguageWire's Smart Editor
 * needs the HTML file to be located there in order to
 * show a preview during the translation process.
 */
final class PreviewSiteIndexFileMover extends PreviewSiteCleanupActionBase {

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

    if (count($indexFiles) != 1) {
      throw new InvalidIndexFileAmountException(count($indexFiles));
    }

    $indexFile = $indexFiles[0];
    $rootPath = $htmlPreviewResult->getHtmlPreviewFolderPath();
    $targetPath = sprintf("%s/index.html", $rootPath);
    rename($indexFile->getRealPath(), $targetPath);

    return $htmlPreviewResult;
  }

  /**
   * Checks if the given file is an index.html file.
   */
  private function isIndexFile(\SplFileInfo $file): bool {
    return $file->getFilename() == "index.html";
  }

}
