import { ChangeDetectionStrategy, Component, Input, OnChanges } from '@angular/core';
import { get, isFunction, isNullOrUndefined } from '@bixi/core/utils';
import { IOperationsCol, IOperationsColBtn, IRow } from '../table.type';
import { ColBase } from './col.base';

@Component({
  selector: 'bixi-table-col-operations',
  host: { '[class.bixi-table-col-operations]': 'true' },
  template: `
    <bixi-col-operations-template [operations]="_operations" [row]="row" [rowIndex]="index"></bixi-col-operations-template>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class BixiTableColOperationsComponent extends ColBase implements OnChanges {
  @Input() col: IOperationsCol;
  _operations: IOperationsColBtn[];

  ngOnChanges() {
    this.reRender();
  }

  private genSubButtons(buttons: IOperationsColBtn[] | undefined): IOperationsColBtn[] {
    if (!buttons || buttons.length === 0) {
      return [];
    }
    // TODO: refactor this code
    return buttons.map(o => {
      o.disabled = isNullOrUndefined(o.disabled) ? false :
        (isFunction(o.disabled) ? (o.disabled as ((row: IRow, index: number) => boolean))(this.row, this.index) : o.disabled);
      o.visible = isNullOrUndefined(o.visible) ? true :
        (isFunction(o.visible) ? (o.visible as ((row: IRow, index: number) => boolean))(this.row, this.index) : o.visible);
      o.tooltip = isNullOrUndefined(o.tooltip) ? false :
        (isFunction(o.tooltip) ? (o.tooltip as ((row: IRow, index: number) => boolean))(this.row, this.index) : o.tooltip);
      o.onClick = isFunction(o.onClick) ? o.onClick : () => void 0;
      const children = this.genSubButtons(o.children);
      // 如果 children 全部都不可见，那么自身也没有必要可见
      if (children && children.length && children.every(c => !c.visible)) {
        o.visible = false;
      }
      o.children = children;
      return o;
    });
  }

  reRender() {
    this._operations = this.genSubButtons((get(this.col, 'operations', () => {
      return [];
    }) as (row: IRow, index: number) => IOperationsColBtn[])(this.row, this.index));
  }
}


