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

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

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

	displayedColumns: string[] = ['nombre', 'created_at', 'actions'];
	dataSourceServicios: MatTableDataSource<Servicios>;

	//Loadings
	isLoading = true;
	showMessageWait = true;

	deleted_at = '0';

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

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

	ngOnInit() {
	}

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

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

		this.lastLength = filterValue.length;
	}

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

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

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

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

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

			let reactivate = (servicios.deleted_at != null)
			
			this.api.servicios.delete(servicios.id, reactivate).subscribe(() => {
				this.getServicios();
				this.layoutUtilsService.showActionNotification(deleteMessage, MessageType.Delete);
			}, () => {
				this.layoutUtilsService.showActionNotification(errorMessage, MessageType.Delete);
			});
		});

	}

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

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

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

}
