import { Component, OnInit, ViewChild } from '@angular/core';
import { NbDialogRef } from '@nebular/theme';
import { ArrayUtils } from '../../../utilities/array-utils';
import { FancyColumn } from '../fancy-row-column.model';
import { FancySelection } from '../fancy-selection.model';
import { FancySettings } from '../fancy-settings.model';
import { FancyTableComponent } from '../fancy-table.component';

export const TABLE_PICKER_COL_CHECK_NAME = 'uiChecked';
const COL_ID = 'id';
@Component({
  selector: 'ngx-table-picker',
  templateUrl: './table-picker.component.html',
  styleUrls: ['./table-picker.component.scss']
})
export class TablePickerComponent implements OnInit {

  @ViewChild(FancyTableComponent) fancyTable: FancyTableComponent<any>;
  title: string;
  data: any[];
  selectedIds: string[];
  settings: FancySettings;
  displaySubmitBtn: boolean;
  datum: any;
  cardCssClass: string = 'nbCard';
  constructor(
    private dlgRef: NbDialogRef<TablePickerComponent>
  ) { }

  ngOnInit() {
    if (this.settings.multiselect && !this.settings.columns.find(c => c.name == TABLE_PICKER_COL_CHECK_NAME)) {

      this.settings.columns.unshift(
        new FancyColumn({ name: TABLE_PICKER_COL_CHECK_NAME, type: 'checkall', widthPx: 20 })
      );
    }
    if (this.settings.dialogCssClass) {
      this.cardCssClass = this.settings.dialogCssClass;
    }
    for (let i = 0; i < this.data.length; i++) {
      const element = this.data[i];
      element[TABLE_PICKER_COL_CHECK_NAME] = this.selectedIds.includes(element[COL_ID]);
    }

    setTimeout(() => {
      if (!this.settings.multiselect) {
        this.fancyTable.searchRowAndFocus(r => r[COL_ID] == this.selectedIds[0]);
      }
    }, 200);
  }
  submit() {
    if (this.settings.multiselect) {
      this.removeCheckboxCol();
      this.dlgRef.close(this.data.filter(d => d[TABLE_PICKER_COL_CHECK_NAME]));
    } else {
      //let selectedId = this.fancyTable.getSelected().focusedRow[COL_ID];
      this.dlgRef.close(this.fancyTable.getSelected().focusedRow);

    }
  }
  close() {
    this.removeCheckboxCol();
    this.dlgRef.close(null);
  }
  removeCheckboxCol() {
    if (this.settings.multiselect) {
      this.settings.multiselect = false;
      this.settings.columns.splice(0, 1);
    }
  }

  doubleClickRow(select: FancySelection<any>) {
    if (this.displaySubmitBtn) {
      if (!this.settings.multiselect) {
        this.dlgRef.close(select.focusedRow);
      } else {
        this.data[select.index][TABLE_PICKER_COL_CHECK_NAME] = !this.data[select.index][TABLE_PICKER_COL_CHECK_NAME];
      }
    } else {
      let editContextMenuItem = this.settings.contextMenuItems.find(c => c.id == 'edit');
      if (editContextMenuItem) {
        editContextMenuItem.callback(select.focusedRow, null);
      }
    }

  }
  selectRow(select: FancySelection<any>) {
    if (select) {
      this.datum = select.focusedRow;
    }
  }
}
