<?php
namespace nur\v\bs3\vc;

use nur\b\params\Tparametrable;
use nur\b\ValueException;
use nur\func;
use nur\v\vo;

/**
 * Class CListGroup: afficher une liste d'éléments
 */
class CListGroup extends _CItemList {
  use Tparametrable;

  const CONTAINER = null;

  const PARAMETRABLE_PARAMS_SCHEMA = [
    "list_group_class" => ["?array", null, "classe CSS de la liste"],
    "container" => ["string", "ul", "container de la liste: ul ou div"],
    "item_func" => ["?callable", null, "fonction avec la signature (\$vs, \$item) retournant l'élément à afficher"],
  ];

  function __construct(?iterable $items=null, ?array $params=null) {
    self::set_parametrable_params_defaults($params, [
      "container" => static::CONTAINER,
    ]);
    parent::__construct($items, $params);
  }

  protected $ppListGroupClass;

  private $ctag, $itag;

  function pp_setContainer(string $container): self {
    switch ($container) {
    case "ul":
      $this->ctag = "ul";
      $this->itag = "li";
      break;
    case "div":
      $this->ctag = "div";
      $this->itag = "a";
      break;
    default:
      throw ValueException::invalid_value($container, "container");
    }
    return $this;
  }

  /** @var array */
  protected $itemCtx;

  function pp_setItemFunc($itemFunc): void {
    if ($itemFunc === null) $this->itemCtx = null;
    else $this->itemCtx = func::_prepare($itemFunc);
  }

  /** retourner le contenu associé au conteneur */
  function container(): ?array {
    return null;
  }

  protected function _printStartContainer($container): void {
    vo::start($this->ctag, [
      "class" => ["list-group", $this->ppListGroupClass],
      $this->container(),
    ]);
  }

  function printStartContainer(): void {
    $this->_printStartContainer($this->container());
  }

  function printEndContainer(): void {
    vo::end($this->ctag);
  }

  /** retourner le contenu associé à l'élément spécifié. */
  function item($item): ?iterable {
    $vs = [$item];
    if ($this->itemCtx !== null) {
      $vs = func::_call($this->itemCtx, [$vs, $item]);
    }
    return $vs;
  }

  protected function _printStartItem(): void {
    vo::start($this->itag, [
      "class" => "list-group-item",
    ]);
  }
  protected function _printEndItem(): void {
    vo::end($this->itag);
  }

  protected function _printItem($item): void {
    vo::tag($this->itag, [
      "class" => "list-group-item",
      $item,
    ], true);
  }

  function printItem($item): void {
    $this->_printItem($this->item($item));
  }
}
