<?php
declare(strict_types=1);

namespace WP_AUX\Entities\AuxFramework\Partials;

use WHOOP\Entities\Elements\Comment;
use WHOOP\Entities\Elements\Ul;
use WP_AUX\Enum\IconsEnum;

/**
 * Represents a collection of header utility nav items
 * @since 1.0.0
 */
class HeaderUtilityNavEntity
{
  /**
   * @var string The ID of the dropdown menu opener button
   */
  protected static string $id;
  /**
   * @var string Base class on the menu block container and the opener button
   */
  protected static string $baseClass;
  /**
   * @var string Readable label for the menu and the button
   */
  protected static string $label;
  /**
   * @var string Class to use on the container around the items list
   */
  protected static string $itemContainerClass;
  /**
   * @var string Class to use on the items list UL
   */
  protected static string $itemListClass;
  /**
   * @var string Class to use on each item link
   */
  protected static string $itemClass;
  /**
   * @var bool Support an optional description on each item
   */
  protected static bool $itemAllowDescription = false;
  /**
   * @var IconsEnum Icon to use in the opener button
   */
  protected static IconsEnum $icon;

  protected Ul $ul;
  protected array $items = [];

  public function __construct()
  {
    $this->ul = Ul::create('', [
      'class' => static::$itemListClass . ' dropdown-items',
      'aria-label' => static::$label . ' dropdown',
    ]);
  }

  /**
   * Add a link with an array containing at least 'url', 'title', and 'description'
   * @since 1.0.0
   */
  public function addLink(array $link): ?HeaderUtilityNavItemEntity
  {
    // Catch invalid/incomplete link and add an HTML comment in its place
    if (!is_array($link)) {
      $node = Comment::create('Invalid/incomplete link');
      $this->ul->appendElement($node);

      return null;
    }

    $item = HeaderUtilityNavItemEntity::create($link, $this);

    $this->items[] = $item;

    return $this->ul->appendElement($item);
  }

  public function getItemClass(): string
  {
    return static::$itemClass;
  }

  public function getItemAllowDescription(): bool
  {
    return static::$itemAllowDescription;
  }

  /**
   * If there are items, render the Quicklinks
   * @since 1.0.0
   */
  public function __toString(): string
  {
    if (empty($this->items)) {
      return '';
    }

    $icon = new IconEntity(static::$icon);

    return '<div class="utility-nav__' . static::$baseClass . '-container menu-item--dropdown">
              <button class="utility-nav__' . static::$baseClass . ' dropdown-toggle" type="button" id="' . static::$id . '" data-toggle="dropdown" aria-expanded="false" aria-pressed="false">
                ' . $icon . static::$label . '
              </button>
              <div class="' . static::$itemContainerClass . ' dropdown">
                ' . (string) $this->ul . '
              </div>
            </div>';
  }

  public static function create(): static
  {
    return new static();
  }
}
