<?php
namespace nur\sery\file\csv;

use nur\sery\cl;
use nur\sery\file\web\Upload;
use nur\sery\os\path;
use nur\sery\ValueException;

trait TAbstractReader {
  /** @param Upload|string|array $reader */
  static function with($reader, ?array $params=null): IReader {
    if ($reader instanceof self) return $reader;
    $class = null;
    if ($reader instanceof Upload) {
      if ($reader->isExt(".csv")) {
        $class = CsvReader::class;
      } else {
        $class = static::class;
        if ($reader->isExt(".ods")) {
          $params["ss_type"] = "ods";
        } else {
          $params["ss_type"] = "xlsx";
        }
      }
      return new $class($reader->tmpName, $params);
    }

    if (is_string($reader)) {
      $params["input"] = $reader;
    } elseif (is_array($reader)) {
      $params = cl::merge($reader, $params);
    } elseif ($reader !== null) {
      throw ValueException::invalid_type($reader, self::class);
    }

    $input = $params["input"] ?? null;
    $ssType = null;
    if (is_string($input)) {
      $ext = path::ext($input);
      if ($input === "-" || $ext === ".csv") {
        $class = CsvReader::class;
      } elseif ($ext === ".ods") {
        $ssType = "ods";
      } elseif ($ext === ".xlsx") {
        $ssType = "xlsx";
      } else {
        $ssType = "xlsx";
      }
    }
    $params["ss_type"] = $ssType;
    if ($class === null) $class = static::class;
    return new $class(null, $params);
  }
}
