<?php

declare(strict_types=1);

namespace Drupal\languagewire_translation_provider\Content\HtmlPreview;

use Drupal\languagewire_translation_provider\Adapter\SystemInterface;

/**
 * Html Preview Settings Checker.
 */
class HtmlPreviewSettingsChecker {
  const PREVIEW_SITE_MODULE_NAME = 'preview_site';
  const PREVIEW_SITE_MINIMUM_VERSION = '1.1.2';
  const ERROR_PREVIEW_SITE_MISSING = 'Preview Site module not installed';
  const ERROR_PREVIEW_SITE_VERSION_MISMATCH = 'Preview Site module (version %s) does not meet the minimum required version %s';
  const ERROR_PRIVATE_FILE_PATH_NOT_SET = 'Private filesystem folder is not set. Please define $settings[\'file_private_path\'] in your site\'s settings.local.php file';

  /**
   * System.
   *
   * @var \Drupal\languagewire_translation_provider\Adapter\SystemInterface
   */
  private SystemInterface $system;

  /**
   * Constructs a new HtmlPreviewSettingsChecker object.
   *
   * @param \Drupal\languagewire_translation_provider\Adapter\SystemInterface $system
   *   System.
   */
  public function __construct(SystemInterface $system) {
    $this->system = $system;
  }

  /**
   * Can generate HTML preview.
   */
  public function canGenerateHtmlPreview(): bool {
    return count($this->getFailedRequirements()) == 0;
  }

  /**
   * Get failed requirements.
   */
  public function getFailedRequirements(): array {
    $errors = [];
    $errors = $this->getPrivateFileSystemError($errors);
    return $this->getPreviewSiteModuleErrors($errors);
  }

  /**
   * Get private file system error.
   */
  private function getPrivateFileSystemError(array $errors): array {
    $privateFilePath = $this->system->realPath("private://");
    if (empty($privateFilePath)) {
      $errors[] = self::ERROR_PRIVATE_FILE_PATH_NOT_SET;
    }
    return $errors;
  }

  /**
   * Get preview site module errors.
   */
  private function getPreviewSiteModuleErrors(array $errors): array {
    $previewSiteVersion = $this->system->moduleVersion(self::PREVIEW_SITE_MODULE_NAME);
    if ($previewSiteVersion === NULL) {
      $errors[] = self::ERROR_PREVIEW_SITE_MISSING;
      return $errors;
    }

    $previewSiteVersionMatch = version_compare($previewSiteVersion, self::PREVIEW_SITE_MINIMUM_VERSION) >= 0;
    if (!$previewSiteVersionMatch) {
      $errors[] = sprintf(self::ERROR_PREVIEW_SITE_VERSION_MISMATCH, $previewSiteVersion, self::PREVIEW_SITE_MINIMUM_VERSION);
    }

    return $errors;
  }

}
