import {Component, Input, OnInit} from '@angular/core';
import {AlertController, ModalController} from '@ionic/angular';
import {uuid_v4} from '../../../../utility';

@Component({
  selector: 'editor-database-columns',
  templateUrl: './columns.component.html',
  styleUrls: ['./columns.component.scss'],
})
export class ColumnsComponent implements OnInit {
  @Input() columnSets: Array<{headerName: string, field: string, Type: string, additionalData: any}> = [];

  constructor(
      protected modals: ModalController,
      protected alerts: AlertController,
  ) { }

  ngOnInit() {}

  onAddColumnClick() {
    this.columnSets.push({headerName: '', field: uuid_v4(), Type: '', additionalData: {}});
  }

  onAddOption(i) {
    const set = this.columnSets[i];
    if ( !Array.isArray(set.additionalData.options) ) {
      set.additionalData.options = [];
    }

    set.additionalData.options.push({value: ''});
  }

  onDeleteOptionClick(i, n) {
    const set = this.columnSets[i];
    set.additionalData.options = set.additionalData.options.filter((x, index) => index !== n);
  }

  dismissModal(doSave = true) {
    if ( doSave ) {
      this.columnSets = this.columnSets.map(x => {
        if ( !x.field ) {
          x.field = uuid_v4();
        }
        return x;
      });

      this.modals.dismiss(this.columnSets);
    } else {
      this.modals.dismiss();
    }
  }

  onDeleteClick(i) {
    this.alerts.create({
      header: 'Delete column?',
      message: 'Are you sure you want to delete this column? Its data will be lost.',
      buttons: [
        { text: 'Keep It', role: 'cancel' },
        {
          text: 'Delete It',
          handler: () => {
            this.columnSets = this.columnSets.filter((x, index) => {
              return index !== i;
            });
          },
        }
      ],
    }).then(alert => alert.present());
  }

  onUpArrow(i) {
    if ( this.columnSets[i - 1] ) {
      const temp = this.columnSets[i];
      this.columnSets[i] = this.columnSets[i - 1];
      this.columnSets[i - 1] = temp;
    }
  }

  onDownArrow(i) {
    if ( this.columnSets[i + 1] ) {
      const temp = this.columnSets[i];
      this.columnSets[i] = this.columnSets[i + 1];
      this.columnSets[i + 1] = temp;
    }
  }

  iteratePin(i) {
    if ( !this.columnSets[i].additionalData.pinned ) {
      this.columnSets[i].additionalData.pinned = 'left';
    } else if ( this.columnSets[i].additionalData.pinned === 'left' ) {
      this.columnSets[i].additionalData.pinned = 'right';
    } else {
      delete this.columnSets[i].additionalData.pinned;
    }
  }
}
