<?php
namespace nur\v\base;

use nur\A;
use nur\v\model\ITagsManager;

class TagsManager implements ITagsManager {
  function __construct() {
    $this->stack = [[
      "mark" => null,
      "end" => null,
    ]];
    $this->index = 0;
  }

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

  /** @var int */
  protected $index;

  function push($mark, ?array $start=null, ?array $end=null): ?array {
    A::append_nn($content, $start);
    $this->stack[] = [
      "mark" => $mark,
      "end" => $end,
    ];
    $this->index++;
    return $content;
  }

  protected function haveMark($mark): bool {
    $index = $this->index;
    while ($index > 0) {
      $item = $this->stack[$index--];
      if ($item["mark"] === $mark) return true;
    }
    return false;
  }

  function pop($mark): ?array {
    if (!$this->haveMark($mark)) return null;
    $content = null;
    while ($this->index > 0) {
      $item = array_pop($this->stack);
      $this->index--;
      A::append_nn($content, $item["end"]);
      if ($item["mark"] === $mark) break;
    }
    return $content;
  }
}
