import {AfterViewInit, ChangeDetectorRef, Component, OnInit} from '@angular/core';
import {MatTableDataSource} from '@angular/material';
import {ApiService} from '../../../../../core/api/api.service';
import {ActivatedRoute, Router} from '@angular/router';
import {LayoutUtilsService, MessageType} from '../../../../../core/_base/crud';
import {TiposVehiculo} from '../tipos-vehiculo.model';

@Component({
  selector: 'kt-tipos-vehiculo-list',
  templateUrl: './tipos-vehiculo-list.component.html',
  styleUrls: ['./tipos-vehiculo-list.component.scss']
})
export class TiposVehiculoListComponent implements OnInit {
  //Search
  lastLength = 0;
  typingTimer;
  typingInterval = 700;

  displayedColumns: string[] = ['nombre', 'objetivo_mensual', 'created_at', 'actions'];
  dataSourceTiposVehiculo: MatTableDataSource<TiposVehiculo>;

  //Loadings
  isLoading = true;
  showMessageWait = true;

  //Paginator, Searcher
  searchText: string;
  sortBy = 'nombre';
  order = 'asc';
  page = '1';
  perPage = '10';
  total = 0;
  pages = [10, 25, 50, 100];
  titulo = 'Tipos de Vehículo';

  constructor(private api: ApiService,
        private router: Router,
        private layoutUtilsService: LayoutUtilsService,
        private activatedRoute: ActivatedRoute,
        private ref: ChangeDetectorRef) {
    this.dataSourceTiposVehiculo = new MatTableDataSource<TiposVehiculo>();
  }

  ngOnInit() {
  }

  getTiposVehiculo(){
    this.isLoading = true;
    this.api.tiposVehiculos.index(this.page, this.searchText, this.sortBy, this.order, this.perPage).subscribe(res =>{
      this.isLoading = false;
      this.showMessageWait = false;
      this.dataSourceTiposVehiculo.data = res.data;
      this.total = res.total;
      this.ref.detectChanges();
    }, ()=>{
      this.isLoading = false;
      this.showMessageWait = false;
    })
  }

  //Search
  filtrarBusqueda(filterValue: string) {
    if (filterValue.length != 0) {
      this.searchText = filterValue.trim().toLowerCase();
      this.getTiposVehiculo();
    } else if (this.lastLength != 0) {
      this.searchText = '';
      this.getTiposVehiculo();
    }

    this.lastLength = filterValue.length;
  }

  onKeyUp(ev) {
    clearTimeout(this.typingTimer);
    this.typingTimer = setTimeout(() => {
      this.filtrarBusqueda(ev.target.value)
    }, this.typingInterval);
  }

  onKeyDown() {
    this.showMessageWait = true;
    this.dataSourceTiposVehiculo.data = [];
    clearTimeout(this.typingTimer);
  }//Fin search

  editTiposVehiculo(id) {
    this.router.navigate(['../tipos-vehiculo/edit/', id], {relativeTo: this.activatedRoute})
  }

  deleteTiposVehiculo(tiposVehiculo) {
    let title = 'Eliminar tipo de vehículo';
    let name = (tiposVehiculo.nombre)? tiposVehiculo.nombre : '';
    let description = '¿Está seguro de eliminar el tipo de vehículo ' + name + '?';
    let waitDesciption = 'Eliminando tipo de vehículo...';
    let deleteMessage = `El tipo de vehículo ha sido eliminado con éxito`;
    let errorMessage = `El tipo de vehículo no se ha podido eliminar`;

    let dialogRef = this.layoutUtilsService.deleteElement(title, description, waitDesciption);
    dialogRef.afterClosed().subscribe(res => {
      if (!res) {
        return;
      }
      this.api.tiposVehiculos.delete(tiposVehiculo.id).subscribe(() => {
        this.getTiposVehiculo();
        this.layoutUtilsService.showActionNotification(deleteMessage, MessageType.Delete);
      }, () => {
        this.layoutUtilsService.showActionNotification(errorMessage, MessageType.Delete);
      });
    });

  }

  sort(event) {
    this.order = event.direction;
    this.sortBy = event.active;
    this.getTiposVehiculo();
  }

  paginator(event) {
    let nextPage = event.pageIndex + 1;
    this.page = nextPage.toString();
    this.perPage = event.pageSize.toString();
    this.getTiposVehiculo();
  }

  ngAfterViewInit(): void {
    this.getTiposVehiculo();
  }
}
