<?php
namespace nur\mapper\fsv;

use nur\A;
use nur\mapper\base\Tparams_command;

/**
 * Class FsvWriter_command: classe de support pour construire une instance de
 * {@link FsvWriter} pour une application recevant des commandes utilisateurs
 */
class FsvWriter_command {
  use Tparams_command;

  const NAME = "outfsv";
  const DEF = [self::NAME, "outv", 
    "help" => "configurer le fichier en sortie au format FSV",
    "action" => [self::class, "create_command"],
    "cmd_args" => [
      "usage" => self::NAME." [file]",
      ["-r", "--run-code", "args" => "value",
        "action" => [self::class, "set_schema_from_code"],
        "help" => "exécuter le code et utiliser sa valeur de retour comme schéma",
      ],
      ["-f", "--run-file", "args" => "file",
        "action" => [self::class, "set_schema_from_file"],
        "help" => "exécuter le fichier et utiliser sa valeur de retour comme schéma",
      ],
      ["-t", "--output-encoding", "args" => "value",
        "action" => [self::class, "set_output_encoding"],
      ],
      ["-o", "--param", "args" => "value",
        "action" => [self::class, "add_params"],
        "help" => "spécifier une option générique",
      ],
      ["args" => [["file"]],
        "action" => [self::class, "set_file"],
      ],
    ],
  ];

  const O_OPTION = ["-o", "--output", "args" => "file",
    "action" => [self::class, "set_file"],
  ];
  const T_OPTION = ["-t", "--output-encoding", "args" => "value",
    "action" => [self::class, "set_output_encoding"],
  ];

  /** @var FsvWriter */
  protected static $command;

  static function create_command() {
    self::$command = new FsvWriter();
  }

  static function set_schema_from_code(string $code) {
    $schema = eval($code);
    self::get()->setFsvSchema($schema);
  }

  static function set_schema_from_file(string $file) {
    $schema = require($file);
    self::get()->setFsvSchema($schema);
  }

  static function set_file($file) {
    $file = A::last(A::with($file));
    self::get()->setOutput($file);
  }

  static function set_output_encoding(string $output_encoding) {
    self::get()->setEncodingFilter($output_encoding);
  }
}
