<?php
namespace nur\mapper\item;

use nur\mapper\base\mapper_utils;
use nur\mapper\base\mappers_command;
use nur\mapper\base\Tparams_command;
use nur\types;

/**
 * Class AttributeFilterMapper_command: classe de support pour construire une
 * instance de mapper pour une application recevant des commandes utilisateurs
 */
class AttributeFilterMapper_command {
  use Tparams_command;

  const NAME = "sela";
  const DEF = [self::NAME,
    "help" => "filtrer et mapper des attributs",
    "action" => [self::class, "create_command"],
    "cmd_args" => [
      "usage" => self::NAME." [name[=default]...]",
      ["-a", "--add-fields", "args" => ["value", [null]],
        "action" => [self::class, "set_add_fields"],
      ],
      ["-r", "--remove-fields", "args" => ["value", [null]],
        "action" => [self::class, "set_remove_fields"],
      ],
      ["-o", "--param", "args" => "value",
        "action" => [self::class, "add_params"],
        "help" => "spécifier une option générique",
      ],
      ["args" => [["value", null]],
        "action" => [self::class, "set_fields"],
      ],
    ],
  ];

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

  static function create_command() {
    self::$command = mappers_command::add(new AttributeFilterMapper());
  }

  static function set_fields(array $names) {
    $fields = [];
    foreach ($names as $name) {
      if (mapper_utils::split_param($name, $name, $type, $value)) {
        if ($type !== null) $value = types::with($type, $value);
        $fields[$name] = $value;
      } else {
        $fields[] = $name;
      }
    }
    if ($fields) self::$command->setFields($fields);
  }

  static function set_add_fields(array $names) {
    $fields = [];
    foreach ($names as $name) {
      if (mapper_utils::split_param($name, $name, $type, $value)) {
        if ($type !== null) $value = types::with($type, $value);
        $fields[$name] = $value;
      } else {
        $fields[] = $name;
      }
    }
    self::$command->setAddFields($fields);
  }

  static function set_remove_fields(array $names) {
    $fields = [];
    foreach ($names as $name) {
      mapper_utils::split_param($name, $name, $type, $value);
      $fields[] = $name;
    }
    self::$command->setRemoveFields($fields);
  }
}
