<?php
namespace nur\sery;

use nur\sery\file\FileReader;
use nur\sery\file\FileWriter;
use nur\sery\file\MemoryStream;
use nur\sery\file\SharedFile;
use nur\sery\file\TempStream;
use nur\sery\file\TmpfileWriter;

/**
 * Class file: outils pour gérer les fichiers
 */
class file {
  static function fix_dash($file) {
    if ($file === "-") $file = null;
    return $file;
  }

  static function reader($input, ?callable $func=null): FileReader {
    $file = new FileReader(self::fix_dash($input));
    if ($func !== null) {
      try {
        $func($file);
      } finally {
        $file->close();
      }
    }
    return $file;
  }
  
  static function writer($output, ?string $mode=null, ?callable $func=null): FileWriter {
    $file = new FileWriter(self::fix_dash($output), $mode);
    if ($func !== null) {
      try {
        $func($file);
      } finally {
        $file->close();
      }
    }
    return $file;
  }

  static function shared($file, ?callable $func=null): SharedFile {
    $file  = new SharedFile($file);
    if ($func !== null) {
      try {
        $func($file);
      } finally {
        $file ->close();
      }
    }
    return $file;
  }

  static function tmpwriter($destdir=null, ?callable $func=null): TmpfileWriter {
    $file = new TmpfileWriter($destdir);
    if ($func !== null) {
      try {
        $func($file);
      } finally {
        $file->close();
      }
    }
    return $file;
  }

  static function memory(?callable $func=null): MemoryStream {
    $file = new MemoryStream();
    if ($func !== null) {
      try {
        $func($file);
      } finally {
        $file->close();
      }
    }
    return $file;
  }

  static function temp(?callable $func=null): TempStream {
    $file = new TempStream();
    if ($func !== null) {
      try {
        $func($file);
      } finally {
        $file->close();
      }
    }
    return $file;
  }
}
