import { AfterViewInit, Component, Input, OnInit, ViewChild } from '@angular/core';
import { MatPaginator, MatSort, MatTableDataSource } from '@angular/material';
import { ReservationPassengerDialogService } from '../reservation-passenger-dialog/services/reservation-passenger-dialog.service';
import { DecimalPipe } from '@angular/common';
import * as moment from 'moment';

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


  @Input() mode;

  decimalParameter = 2;

  @ViewChild('paginator', { static: true }) paginator: MatPaginator;
  @ViewChild(MatSort, { static: false }) sort: MatSort | undefined;

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

  displayedColumns: string[] = ['id', 'agent', 'passenger', 'actions'];
  dataSource !: MatTableDataSource<any>;

  constructor(
    private reservationPassengerDialogService: ReservationPassengerDialogService,
    private decimalPipe: DecimalPipe,
  ) { }

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

  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');
  }

  ngOnInit(): void {
    this.dataSource = new MatTableDataSource<any>();
  }


  onEdit(item) {
    this.reservationPassengerDialogService.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);
        }
      }
    )
  }

  onDelete(item) {
    let dataSource = [...this.dataSource.data];
    let pos = dataSource.findIndex(x => x === item)
    dataSource.splice(pos, 1)
    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;
  }

  onCreate() {
    this.reservationPassengerDialogService.loadComponent(null, this.mode, this.getMaxDate()).subscribe(
      data => {
        if (data !== null) {
          let datase = [];
          datase.push(data)
          console.log(datase);
          this.dataSource = new MatTableDataSource(datase);
        }
      }
    )
  }

}
