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 {Vehiculos} from '../vehiculos.model';

@Component({
  selector: 'kt-vehiculos-list',
  templateUrl: './vehiculos-list.component.html',
  styleUrls: ['./vehiculos-list.component.scss']
})
export class VehiculosListComponent implements OnInit {

  //Search
	lastLength = 0;
	typingTimer;
	typingInterval = 700;

	displayedColumns: string[] = ['num_economico', 'descripcion', 'tipo_vehiculo', 'sucursal', 'created_at', 'actions'];
	dataSourceVehiculos: MatTableDataSource<Vehiculos>;

	//Loadings
	isLoading = true;
	showMessageWait = true;

	deleted_at = '0';

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

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

	ngOnInit() {
	}

	toggle(event){
		this.deleted_at = event.checked == false ? '0' : '1';
		this.getVehiculos();
	}

	getVehiculos(){
		this.isLoading = true;
		this.api.vehiculos.index(this.page, this.searchText, this.sortBy, this.order, this.perPage,null, this.deleted_at).subscribe(res =>{
			this.isLoading = false;
			this.showMessageWait = false;
			this.dataSourceVehiculos.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.getVehiculos();
		} else if (this.lastLength != 0) {
			this.searchText = '';
			this.getVehiculos();
		}

		this.lastLength = filterValue.length;
	}

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

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

	editVehiculo(id) {
		this.router.navigate(['../vehiculos/edit/', id], {relativeTo: this.activatedRoute})
	}

	deleteVehiculo(vehiculo) {
		let title = (!vehiculo.deleted_at) ? 'Eliminar vehículo' : 'Activar vehículo';
		let name = (vehiculo.nombre)? vehiculo.nombre : '';
		let description = (!vehiculo.deleted_at) ? '¿Está seguro de eliminar el vehículo ' + name + '?' : '¿Está seguro de activar el vehículo ' + name + '?';
		let waitDesciption = (!vehiculo.deleted_at) ? 'Eliminando vehículo...' : 'Activando vehículo...';
		let deleteMessage = (!vehiculo.deleted_at) ? `El vehículo ha sido eliminado con éxito` : `El vehículo ha sido activado con éxito`;
		let errorMessage = (!vehiculo.deleted_at) ? `El vehículo no se ha podido eliminar` : `El vehículo no se ha podido activar`;
		let btnText = (!vehiculo.deleted_at) ? 'Eliminar' : 'Activar';

		let dialogRef = this.layoutUtilsService.deleteElement(title, description, waitDesciption, btnText);
		dialogRef.afterClosed().subscribe(res => {
			if (!res) {
				return;
			}

			let reactivated = (vehiculo.deleted_at != null);

			this.api.vehiculos.delete(vehiculo.id, reactivated).subscribe(() => {
				this.getVehiculos();
				this.layoutUtilsService.showActionNotification(deleteMessage, MessageType.Delete);
			}, () => {
				this.layoutUtilsService.showActionNotification(errorMessage, MessageType.Delete);
			});
		});

	}

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

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

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

}
