import { bindable, computedFrom, containerless, processContent, TaskQueue, View } from "aurelia-framework";
import { UIInternal } from "../../../utils/ui-internal";
import { UIColumn } from "./ui-column";
import { UITableAction } from "./ui-table-action";

@containerless()
@processContent((compiler, resources, node, instruction) => {
  instruction.inheritBindingContext = true;
  return true;
})

export class HeaderCell {
  @bindable()
  public column: UIColumn | UITableAction;
  @bindable()
  public applyColspan: Boolean = false;
  @bindable()
  public sortBy: string;
  @bindable()
  public sortOrder: string;

  protected el;
  protected overrideContext: any;
  private view: View;
  private _title: string;

  constructor(private element: Element, private taskQueue: TaskQueue) { }

  public bind(bindingContext: Object, overrideContext?: any) {
    this.overrideContext = overrideContext;
    UIInternal.subscribe(UIInternal.EVT_CHANGE_LANGUAGE, () => {
      this.setTitle();
    });
  }

  protected fireSortEvent() {
    if (this.column.sortable && this.column.dataId != null) {
      this.element.dispatchEvent(UIInternal.createEvent("sort"));
    }
  }

  public attached() {
    this.taskQueue.queueMicroTask(() => {
      this.compileHeader(this.el);
    });
  }

  @computedFrom("_title")
  public get title() {
    return this._title;
  }

  public setTitle() {
    this._title = this.column?.title ? this.column.title : (this.view as any)?.firstChild?.textContent?.trim() ?? '';
  }

  public compileHeader(el: Element): boolean {
    if (el && this.column != null && this.overrideContext != null) {
      const tpl =
        this.column.templateHeader
          ? this.column.templateHeader.outerHTML
          : `<template><span innerhtml.bind="column.label"></span></template>`;

      if (this.overrideContext.parentOverrideContext != null) {
        if (this.overrideContext.parentOverrideContext.parentOverrideContext != null) {
          this.view = UIInternal.compileTemplate(tpl, this, this.overrideContext.parentOverrideContext.parentOverrideContext.__parentOverrideContext);
        }
        else {
          this.view = UIInternal.compileTemplate(tpl, this, this.overrideContext.parentOverrideContext.__parentOverrideContext);
        }
        this.view.appendNodesTo(el);
        this.view.attached();
        this.setTitle();
      }
    }
    return true;
  }

  public isActionColumn() {
    return this.column instanceof UITableAction || this.column.type == "action";
  }
}
