<?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 TAbstractBuilder {
  /** @param Upload|string|array $builder */
  static function with($builder, ?array $params=null): IBuilder {
    if ($builder instanceof self) return $builder;
    $class = null;
    if ($builder instanceof Upload) {
      # faire un builder dans le même format que le fichier uploadé
      if ($builder->isExt(".csv")) {
        $class = CsvBuilder::class;
      } else {
        $class = static::class;
        if ($builder->isExt(".ods")) {
          $params["ss_type"] = "ods";
        } else {
          $params["ss_type"] = "xlsx";
        }
      }
      return new $class($builder->name, $params);
    }

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

    $output = $params["output"] ?? null;
    $ssType = null;
    if (is_string($output)) {
      $ext = path::ext($output);
      if ($output === "-" || $ext === ".csv") {
        $class = CsvBuilder::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);
  }
}
