import { DecimalPipe } from '@angular/common';
import { AfterViewInit, Component, Input, OnInit, ViewChild } from '@angular/core';
import { MatPaginator, MatSort } from '@angular/material';
import { MatTableDataSource } from '@angular/material/table';
import { ColumnTemplate } from '@xdf/gallery';
import * as moment from 'moment';
import { FlightLegDialogService } from '../flight-leg-dialog/services/flight-leg-dialog.service';

@Component({
  selector: 'byte-flight-legs-grid',
  templateUrl: './flight-legs-grid.component.html',
  styleUrls: ['./flight-legs-grid.component.scss']
})
export class FlightLegsGridComponent implements OnInit, AfterViewInit {

  @Input() mode;
  
  columnTemplateArray : ColumnTemplate[] = [
    {
      name: 'arrivalDate',
      sortable: false,
      title: 'Fecha Salida',
      visible: true,
      filtable: true,
      style: { width: '30%' },
      type: 'date',
      aliasName: null,
      queryName: null,
      responsive: null,
      styles: null,
      values: null,
      digitsInfo: null,
      dateFormat: null,
      colStyle: null
    },
    {
      name: 'departureDate',
      sortable: false,
      title: 'Fecha Llegada',
      visible: true,
      filtable: true,
      style: { width: '30%' },
      type: 'date',
      aliasName: null,
      queryName: null,
      responsive: null,
      styles: null,
      values: null,
      digitsInfo: null,
      dateFormat: null,
      colStyle: null
    }
  ];
  decimalParameter = 2;

  dataSource: MatTableDataSource<any>;
  displayedColumns = new Array<string>();
  @ViewChild('paginator',{static: true}) paginator: MatPaginator;
  @ViewChild(MatSort, { static: false }) sort: MatSort | undefined;

  sortDirection = 'desc';
  sortColumn = 'arrivalDate';

  
  constructor(
    private flightLegDialogService : FlightLegDialogService,
    private decimalPipe : DecimalPipe,
  ) {}

  ngAfterViewInit(): void {
    this.paginator.pageSize = 5;
    this.dataSource.paginator = this.paginator;
    this.sort.sortChange.subscribe(() => {
      console.log();
    });
  }

  ngOnInit(): void {
    this.dataSource = new MatTableDataSource<any>();
    this.columnTemplateArray.forEach((column) => {
        console.log(this.dataSource);
        this.displayedColumns.push(column.name);
      }
    );
    this.displayedColumns.push('actions');
  }

  autoSort(data) {
    return data.sort((a, b) => new Date(a.arrivalDate) < new Date(b.arrivalDate) ? 1 : -1);
  }

  numberWithCommas(x): string {
    return x ? this.decimalPipe.transform(x, '1.' + this.decimalParameter + '-' + this.decimalParameter) : '';
  }

  getDateFormat(liquidationDate) {
    return moment(liquidationDate).format('DD-MM-YYYY');
  }


  onCreate() {
    this.flightLegDialogService.loadComponent(null, this.mode, this.getMaxDate()).subscribe(
      data => {
        if(data !== null) {
          let dataSource = this.dataSource.data.slice();
          dataSource.push(data);
          console.log(data);
          this.dataSource.data = this.autoSort(dataSource);
        }
      }
    )
  }

  onDelete(item) {
    let dataSource = [...this.dataSource.data];
    let pos = dataSource.findIndex(x => x === item);
    dataSource.splice(pos, 1);
    this.dataSource.data = this.autoSort(dataSource);
  }

  onEdit(item) {
    this.flightLegDialogService.loadComponent(item, this.mode, this.getMaxDate()).subscribe(
      data => {
        if(data !== null) {
          let dataSource = [...this.dataSource.data];
          let pos = dataSource.findIndex(x => x === item);
          dataSource[pos] = data;
          this.dataSource.data = this.autoSort(dataSource);;
        }
      }
    )
  }

  

  getMaxDate() {
    let maxDate 
    if(this.dataSource.data.length > 0) {
      maxDate = new Date(Math.max.apply(null,this.dataSource.data.map(x => new Date(x.arrivalDate))));
      maxDate.setDate(maxDate.getDate() + 1);
    } else {
      maxDate = new Date();
    }
    return maxDate;
  }

}
