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

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

	displayedColumns: string[] = ['name', 'slug', 'web', 'movil', 'actions'];
	dataSourceRol: MatTableDataSource<Rol>;

	//Loadings
	isLoading = true;
	showMessageWait = true;

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

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

	ngOnInit() {
	}

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

		this.lastLength = filterValue.length;
	}

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

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

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

	deleteRol(rol) {
		let title = 'Eliminar rol';
		let description = '¿Está seguro de eliminar el rol ' + rol.name + '?';
		let waitDesciption = 'Eliminando rol...';
		let deleteMessage = `El rol ha sido eliminado con éxito`;
		let errorMessage = `El rol no se ha podido eliminar`;
		let btnTex = 'Eliminar'

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

	}

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

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

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