import { Component, OnInit, ChangeDetectionStrategy, Input } from '@angular/core';
import { NbDialogRef } from '@nebular/theme';
import { Observable } from 'rxjs';
import { first } from 'rxjs/operators';
import { DropDownOption } from '../../../entity/dropDownOption';
import { FancyColumn } from '../fancy-row-column.model';
import { FancyEditorInstance } from '../fancy-selection.model';

@Component({
  selector: 'ngx-fancy-table-editor',
  templateUrl: './fancy-table-editor.component.html',
  styleUrls: ['./fancy-table-editor.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class FancyTableEditorComponent implements OnInit {
  @Input() columns: FancyColumn[];
  @Input() datum: any;
  isAdding: boolean = false;
  editingInstance: any
  dropdownSource: DropDownOption[];
  index: number;
  validationMsg: string = null;
  validation: (obj: FancyEditorInstance) => Observable<string> | string;
  constructor(protected dialogRef: NbDialogRef<FancyTableEditorComponent>
  ) { }

  ngOnInit() {

    this.editingInstance = Object.assign({}, this.datum);
    this.columns = [...this.columns].sort((a, b) => (a.editingFieldIndex ? a.editingFieldIndex : 0) - (b.editingFieldIndex ? b.editingFieldIndex : 0));
  }

  cancel() {
    this.dialogRef.close();
  }

  submit() {
    this.validationMsg = null;
    let async = false;
    if (this.validation) {
      let tempResult = this.validation({ index: this.index, object: this.editingInstance });

      if (null != tempResult) {
        if (typeof tempResult === 'string') {
          this.validationMsg = tempResult;
        } else {
          async = true;
          tempResult.pipe(first()).subscribe(result => {
            this.validationMsg = result;
            if (null === this.validationMsg) {
              this.dialogRef.close(this.editingInstance);
            }
          });
        }
      }

    }

    if (false === async && null === this.validationMsg) {

      this.dialogRef.close(this.editingInstance);
    }
  }

  getDate(datestr: string): Date {
    return new Date(datestr);
  }

  getDateString(event) {

    return event;
  }

}
