/*
Copyright 2022 Pawel Psztyc
Licensed under the CC-BY 2.0
*/
import { html, TemplateResult, LitElement, SVGTemplateResult } from 'lit';
import { property } from 'lit/decorators.js';
import * as Icons from './Icons.js';
import { IconType } from './Icons.js';

export default class UiIcon extends LitElement {
  private iconInternal: IconType | undefined;

  private hasIconInternal = false;

  private iconValue: SVGTemplateResult | undefined;

  /**
   * An icon to be rendered from the ApiIcons library.
   * When incorrect icon is referenced nothing is rendered.
   * @attribute
   */
  @property()
  get icon(): IconType | undefined {
    return this.iconInternal;
  }

  set icon(value: IconType | undefined) {
    const old = this.iconInternal;
    if (old === value) {
      return;
    }
    this.iconInternal = value;
    this.updateIcon(value);
    // don't request update here
  }

  /**
   * @returns True when the icon was found and is rendered.
   */
  get hasIcon(): boolean {
    return this.hasIconInternal;
  }

  /**
   * Maps icon name to it's definition and sets `hasIcon` value.
   *
   * @param name Icon name
   */
  protected updateIcon(name: IconType | undefined): void {
    const icon = (Icons as never)[name as IconType] as SVGTemplateResult | undefined;
    this.hasIconInternal = !!icon;
    this.iconValue = icon;
    this.requestUpdate();
  }

  /**
   * @return Template result for an icon
   */
  override render(): TemplateResult {
    const { hasIcon, iconValue: _iconValue } = this;
    if (!hasIcon) {
      return html`<slot></slot>`;
    }
    return html`${_iconValue}`;
  }
}
