import { DialogReservationCancelComponent } from './../../components/dialog-reservation-cancel/dialog-reservation-cancel.component';
import { ChangeDetectorRef, Component, OnInit, ViewChild, ViewContainerRef } from '@angular/core';
import { PassengerReservationService } from '../../services/passenger-reservation.service';
import { ColumnTemplate, ConfirmationDialogService, DynaDataSource, FieldFilter, extractRSQL } from '@xdf/gallery';
import { TagFilter } from '@xdf/gallery/lib/views/gallery/ngx-tags-input/model/tag-filter';
import { AuthenticationService, NotificationService, NotificationType, Pagination, SortField } from '@xdf/commons';
import { tap } from 'rxjs/operators';
import { ActivatedRoute, Router } from '@angular/router';
import { AgentService } from '../../../supervisor/service/agent.service';
import { TranslateService } from '@ngx-translate/core';
import { MatDialog, MatPaginator, MatSort } from '@angular/material';
import { DialogReservationPayComponent } from '../../components/dialog-reservation-pay/dialog-reservation-pay.component';

const columnTemplateArray = [
  {
    name: 'id',
    sortable: true,
    title: 'reservation_id',
    visible: true,
    filtable: true,
    style: { width: '75px' },
    type: 'number',
    aliasName: null,
    queryName: null,
    responsive: null,
    styles: null,
    values: null,
    digitsInfo: null,
    dateFormat: null,
    colStyle: null
  },
  {
    name: 'airportOrigin',
    sortable: true,
    title: 'reservation_airportOrigin',
    visible: true,
    filtable: true,
    style: { width: '120px' },
    type: 'string',
    aliasName: null,
    queryName: null,
    responsive: null,
    styles: null,
    values: null,
    digitsInfo: null,
    dateFormat: null,
    colStyle: null
  },
  {
    name: 'airportDestination',
    sortable: true,
    title: 'reservation_airportDestination',
    visible: true,
    filtable: true,
    style: { width: '120xp' },
    type: 'string',
    aliasName: null,
    queryName: null,
    responsive: null,
    styles: null,
    values: null,
    digitsInfo: null,
    dateFormat: null,
    colStyle: null
  },
  {
    name: 'departureDate',
    sortable: true,
    title: 'reservation_departureDate',
    visible: true,
    filtable: true,
    style: { width: '120px' },
    type: 'string',
    aliasName: null,
    queryName: null,
    responsive: null,
    styles: null,
    values: null,
    digitsInfo: null,
    dateFormat: null,
    colStyle: null
  },
  {
    name: 'status',
    sortable: true,
    title: 'reservation_status',
    visible: true,
    filtable: true,
    style: { width: '120px' },
    type: 'string',
    aliasName: null,
    queryName: null,
    responsive: null,
    styles: null,
    values: null,
    digitsInfo: null,
    dateFormat: null,
    colStyle: null
  },
  {
    name: 'amount',
    sortable: true,
    title: 'reservation_price',
    visible: true,
    filtable: true,
    style: { width: '120px' },
    type: 'string',
    aliasName: null,
    queryName: null,
    responsive: null,
    styles: null,
    values: null,
    digitsInfo: null,
    dateFormat: null,
    colStyle: null
  }
];

const fieldFilters = [];

@Component({
  selector: 'byte-reservations',
  templateUrl: './reservations.component.html',
  styleUrls: ['./reservations.component.scss']
})
export class ReservationsComponent implements OnInit {

  @ViewChild(MatPaginator, { static: false }) paginator: MatPaginator;
  @ViewChild(MatSort, { static: false }) sort: MatSort;

  sortColumn: string;
  sortDirection: string;
  statusQuickFilter: string;
  pagingSize = 10;
  programIdentifier = 'agent';

  columnTemplateArray: ColumnTemplate[];
  dataSource: DynaDataSource;
  displayedColumns = new Array<string>();
  fieldFilters: Array<FieldFilter> = fieldFilters;
  filterTags = [];
  pagination: Pagination;
  public resourceAuth: any;

  constructor(
    private route: ActivatedRoute,
    private reservationService: PassengerReservationService,
    private notificationService: NotificationService,
    protected confirmationDialogService: ConfirmationDialogService,
    protected vcRef: ViewContainerRef,
    public matDialog: MatDialog
  ) { }

  ngAfterViewInit(): void {
    this.sort.sortChange.subscribe(() => {
      if (!this.sort.disabled && this.sort.active) {
        this.pagination.sortFields = new Array();
        const sortField: SortField = new SortField();
        sortField.direction = this.sortDirection = this.sort.direction;
        sortField.field = this.sortColumn = this.sort.active;
        this.pagination.sortFields.push(sortField);
      }

      this.paginator.pageIndex = 0;
      this.dataSource.load(this.pagination);
    });

    this.paginator.page
      .pipe(
        tap(() => {
          this.pagination.currentPage = this.paginator.pageIndex;
          this.pagination.itemsPerPage = this.paginator.pageSize;
          this.dataSource.load(this.pagination);
        })
      )
      .subscribe();
  }

  ngOnInit() {
    this.sortColumn = 'id';
    this.sortDirection = 'asc';

    const authList = this.route.snapshot.paramMap['authorization'];

    if (authList) {
      this.resourceAuth = new Object();
      authList.forEach(option => {
        this.resourceAuth[option] = true;
      });
    }

    this.columnTemplateArray = columnTemplateArray;

    this.reservationService.serviceURL = '/service/reservations';
    this.dataSource = new DynaDataSource(this.reservationService);

    const previousState = JSON.parse(localStorage.getItem(this.programIdentifier + '-state'));

    if (previousState) {
      const PAG = 'pagination';
      const FILTERS = 'filtersTags';

      this.pagination = previousState[PAG];
      this.filterTags = previousState[FILTERS];

      localStorage.removeItem(this.programIdentifier + '-state');
    } else {

      // Paginación
      this.pagination = new Pagination();
      this.pagination.currentPage = 0;
      this.pagination.itemsPerPage = this.pagingSize;

      this.pagination.filterExpression = 'id != 0';

      // Ordenación por defecto
      if (this.sortColumn && this.sortDirection) {
        this.pagination.sortFields = new Array();
        const sortField: SortField = new SortField();
        sortField.direction = this.sortDirection;
        sortField.field = this.sortColumn;
        this.pagination.sortFields.push(sortField);
      }
    }

    // calculando la columnas a pintar
    this.columnTemplateArray.forEach(column => {
      this.displayedColumns.push(column.name);
    });

    this.displayedColumns.push('actions');

    this.dataSource.load(this.pagination);
  }

  getReservationStatusClass(status: string) {
    switch (status) {
      case 'RESERVED':
        return 'badge badge-pill badge-info py-2 px-1 rounded';
      case 'PAID':
        return 'badge badge-pill badge-success py-2 px-1 rounded';
      case 'CANCELED':
        return 'badge badge-pill badge-danger py-2 px-1 rounded';
      default:
        return '';
    }
  }

  onFilter(tags: Array<TagFilter>) {

    this.filterTags = tags;
    this.pagination.currentPage = 0;

    // let tagsTemp = tags.slice();
    const tagsTemp = tags.map(a => Object.assign({}, a));

    for (let i = 0; i < tagsTemp.length; i++) {
      if (tagsTemp[i].column !== 'id') {
        tagsTemp[i].value = tags[i].value;
      }
    }

    this.pagination.filterExpression = extractRSQL(tagsTemp);

    if (this.pagination.filterExpression === null || this.pagination.filterExpression === undefined) {
      this.pagination.filterExpression = 'id != 0';
    }

    this.dataSource.load(this.pagination);
  }

  onRefresh() {
    this.dataSource.load(this.pagination);
  }

  onPayProcess(pay) {
    const ref = this.matDialog.open(DialogReservationPayComponent, {
      width: '600px',
      data: {
        status: false,
        pay: pay
      }
    });

    ref.afterClosed().subscribe(result => {
      if (result && result.status) {
        const data = { status: 'PAID' };
        this.reservationService.edit(data, pay.id)
          .subscribe(response => {
            this.notificationService.showMessage('Pago realizado con éxito', 'Información', NotificationType.success);
          })
      }
    });
  }

  onCancelProcess(pay) {
    const ref = this.matDialog.open(DialogReservationCancelComponent, {
      width: '400px',
    });

    ref.afterClosed().subscribe(result => {
      if (result) {
        const data = { status: 'CANCELED' };
        this.reservationService.edit(data, pay.id)
          .subscribe(response => {
            this.notificationService.showMessage('Se cancelo la reserva con exito!', 'Información', NotificationType.success);
          })
      }
    });
  }
}
