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

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

	displayedColumns: string[] = ['nombre', 'email', 'telefono', 'role', 'tipo_empleado', 'sucursal', 'created_at', 'actions'];
	dataSourceUsuario: MatTableDataSource<Usuario>;

	//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 = 'Usuarios';

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

	ngOnInit() {
	}

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

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

		this.lastLength = filterValue.length;
	}

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

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

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

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

		let dialogRef = this.layoutUtilsService.deleteElement(title, description, waitDesciption, btnText);
		dialogRef.afterClosed().subscribe(res => {
			if (!res) {
				return;
			}
			let reactivate = (usuario.deleted_at != null)
			this.api.usuarios.delete(usuario.id, reactivate).subscribe(() => {
				this.getUsuarios();
				this.layoutUtilsService.showActionNotification(deleteMessage, MessageType.Delete);
			}, () => {
				this.layoutUtilsService.showActionNotification(errorMessage, MessageType.Delete);
			});
		});

	}

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

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

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