import { bindable, containerless, customElement, DOM, inlineView } from "aurelia-framework";
import { UIInternal } from "../../utils/ui-internal";

@containerless()
@customElement("ui-tag")
@inlineView(
  `<template>
    <a class="ui-tag ui-tag--\${type} ui-tag--\${size} \${uiTheme} \${classes}" class.bind="clickable ? '' : 'ui-tag-readonly'" style.bind="styleObject"
     href.bind="href" ref="vmElement" click.delegate="onClick()">
      <div class="ui-tag__label" title="\${label}">\${label}</div>
      <div class="ui-tag__icon"><slot name="avatar"><ui-icon if.bind="icon" icon.bind="icon"></ui-icon></slot></div>
      <div class="ui-tag__value"><slot></slot></div>
      <div class="ui-tag__close" if.bind="closeable" click.trigger="[$event.stopEvent(), close()]">
        <ui-icon icon="digi-cross"></ui-icon>
      </div>
    </a>
  </template>`
)
export class UITag {
  @bindable()
  public id: string = "";
  @bindable()
  public label: string = "";
  @bindable()
  public icon: string = "";
  @bindable()
  public href: string = null;
  @bindable()
  public onClick: Function = null;
  @bindable()
  public size: "nm" | "md" | "lg" = "nm";
  @bindable()
  public type: "normal" | "solid" = "normal";
  @bindable()
  public beforeCloseFn: Function;
  @bindable()
  public textColor: string = null;
  @bindable()
  public backgroundColor: string = null;
  @bindable()
  public closeable: boolean = false;
  @bindable()
  public clickable: boolean = false;
  @bindable()
  public classes: string = "";

  protected vmElement: HTMLAnchorElement;
  protected style: string = "normal";

  private styleObject: AnyObject = null;
  private uiTheme: string = null;

  constructor(protected element: Element) { }

  public backgroundColorChanged() {
    this.resetColors();
  }

  public textColorChanged() {
    this.resetColors();
  }

  public close(): void {
    if (this.beforeCloseFn) {
      this.beforeCloseFn();
    }
    UIInternal.fireCallbackEvent(this, "beforeclose", this.id).then(b =>
      b ? this.remove() : undefined
    );
  }

  protected bind() {
    this.closeable = !isFalse(this.closeable);
    this.clickable = !isFalse(this.clickable) || this.href != null || this.onClick != null;
    this.resetColors();
  }

  private remove(): void {
    this.element.dispatchEvent(UIInternal.createEvent("close", this.id));
    UIInternal.queueTask(() => {
      if (this.vmElement) {
        DOM?.removeNode(this.vmElement);
      }
    });
  }

  private resetColors() {
    this.uiTheme = null;
    this.styleObject = {};
    if (this.backgroundColor != null) {
      if (this.backgroundColor.startsWith('ui-theme--')) {
        this.uiTheme = this.backgroundColor;
      }
      else {
        this.styleObject['background-color'] = this.backgroundColor;
      }
    }
    if (this.textColor != null && this.uiTheme == null) {
      this.styleObject['color'] = this.textColor;
    }
  }
}
