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

@containerless()
@customElement("menu-item")
@inlineView(`<template>
  <template if.bind="item.group">
    <ui-menu-group label.bind="item.group" hidden-label.bind="item.hiddenLabel">
      <menu-item repeat.for="groupItem of item.items" item.bind="groupItem"></menu-item>
    </ui-menu-group>
  </template>
  <template if.bind="item.label">
    <ui-menu-item label.bind="item.label" href.bind="item.href"
    icon.bind="item.icon" color.bind="item.color" icon-color.bind="item.iconColor" ui-badge="value.bind:item.badge; theme.bind:item.badgeTheme;"
    disabled.bind="typeof item.disabled === 'function' ? item.disabled() : item.disabled"
    active.bind="typeof item.active === 'function' ? item.active() : item.active"
    hide.bind="typeof item.hidden === 'function' ? item.hidden() : item.hidden"
    click.delegate="onClick($event, current)">
      <ui-drop view-model.ref="dropEl" if.bind="item.items" auto-open.bind="false">
        <ui-menu if.bind="dropEl.isOpen" menu-items.bind="item.items" noitems-label.bind="noitemsLabel"></ui-menu>
      </ui-drop>
    </ui-menu-item>
  </template>
  <template if.bind="item === '-'">
    <ui-divider></ui-divider>
  </template>
</template>`)
@processContent((compiler, resources, node, instruction) => {
  instruction.inheritBindingContext = true;
  return true;
})
export class MenuItem {
  @bindable()
  protected item: IMenuItems;
  bind(context, overrideContext) {
    // as the context is inherited, we must define a dropEl object in the current context to avoid using dropEl object from parent (ie in case of multiple menu-item inheritance)
    context.dropEl = null;
  }
  @bindable()
  protected noitemsLabel: string = "No Menu";
  protected onClick($event: MouseEvent, args) {
    // @ts-ignore
    if (this.item.disabled != null && (typeof this.item.disabled === 'function' ? this.item.disabled() : this.item.disabled)) {
      $event.stopPropagation();
      return false;
    }
    // @ts-ignore
    if (this.item.items) {
      $event.stopPropagation();
    }
    // @ts-ignore
    if (this.item.handler) {
      // @ts-ignore      
      this.item.handler(args);
      UIInternal.broadcast(UIInternal.EVT_VIEWPORT_CLICK, $event.target);
    }
    return true;
  }
}