<?php
declare(strict_types=1);

namespace WP_AUX\Entities\AuxFramework\Partials;

use WP_AUX\Enum\IconsEnum;

class IconEntity
{
  public const DEFAULT_ICON_WRAPPER = 'icon-wrapper';

  protected string|IconsEnum|null $icon = null;
  protected ?string $wrap = null;

  public function __construct(string|IconsEnum|null $icon = null) {
    $this->setIcon($icon);
  }

  public function setIcon(string|IconsEnum|null $icon = null) {
    if (is_string($icon)) {
      $icon = IconsEnum::tryFrom($icon);
    }

    $this->icon = $icon;
  }

  public function setWrap(bool|string $wrap): static
  {
    if (is_bool($wrap)) {
      $this->wrap = $wrap ? self::DEFAULT_ICON_WRAPPER : null;
    } else {
      $this->wrap = $wrap;
    }

    return $this;
  }

  public function __toString(): string
  {
    $icon = $this->icon;
    if ($icon instanceof IconsEnum) {
      $icon = $icon->value;
    }

    if (!$icon) {
      return '';
    }

    $iconString = '<svg><use href="#%s"></use></svg>';

    if ($this->wrap) {
      $iconString = sprintf('<div class="%s">%s</div>', $this->wrap, $iconString);
    }

    return sprintf($iconString, $icon);
  }

  public static function create(string|IconsEnum $icon, bool|string $wrap = true): static
  {
    $icon = new static($icon);
    $icon->setWrap($wrap);

    return $icon;
  }
}
