<?php

declare(strict_types=1);

namespace Drupal\languagewire_translation_provider\api\Libraries\Files;

use Drupal\languagewire_translation_provider\api\Libraries\Content\MediaType;
use Drupal\languagewire_translation_provider\api\Libraries\Content\StreamContent;
use Laminas\Diactoros\Stream;

/**
 * Reference File Factory.
 *
 * Reference File Factory class for
 * creating instances of DraftReferenceFile object.
 */
final class ReferenceFileFactory {

  /**
   * Make from text.
   *
   * Creates a plain text DraftReferenceFile
   * object from a content string and a filename.
   *
   * @param string $text
   *   The content of the file.
   * @param string $filename
   *   The filename of the file.
   *
   * @return DraftReferenceFile
   *   The created DraftReferenceFile object.
   */
  public static function makeFromText(string $text, string $filename): DraftReferenceFile {
    $stream = new Stream('php://temp', 'wb+');
    $stream->write($text);
    $stream->rewind();

    $streamContent = new StreamContent($stream, MediaType::PLAIN_TEXT);

    return new DraftReferenceFile($streamContent, $filename);
  }

  /**
   * Creates a DraftReferenceFile object from a file path and a mime type.
   *
   * @param string $filePath
   *   The path to the file.
   * @param string $mimeType
   *   The mime type of the file.
   *
   * @return DraftReferenceFile
   *   The created DraftReferenceFile object.
   */
  public static function makeFromFilePath(string $filePath, string $mimeType): DraftReferenceFile {
    $fileHandle = fopen($filePath, 'rb');

    if ($fileHandle === FALSE) {
      throw new FileNotFoundException("Could not create DraftReferenceFile from path \"$filePath\", file was not found");
    }

    $fileName = basename($filePath);
    $stream = new Stream($fileHandle);
    $streamContent = new StreamContent($stream, $mimeType);

    return new DraftReferenceFile($streamContent, $fileName);
  }

}
