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

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

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

	displayedColumns: string[] = ['nombre', 'domicilio', 'telefono', 'gerente', 'encargado', 'created_at', 'actions'];
	dataSourceSucursales: MatTableDataSource<Sucursales>;

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

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

	ngOnInit() {
	}

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

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

		this.lastLength = filterValue.length;
	}

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

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

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

	deleteSucursal(sucursal) {
		let title = (!sucursal.deleted_at) ? 'Eliminar sucursal' : 'Activar sucursal';
		let name = (sucursal.nombre) ? sucursal.nombre : '';
		let description = (!sucursal.deleted_at) ? '¿Está seguro de eliminar la sucursal ' + name + '?' : '¿Está seguro de activar la sucursal ' + name + '?';
		let waitDesciption = (!sucursal.deleted_at) ? 'Eliminando sucursal...' : 'Activando sucursal...';
		let deleteMessage = (!sucursal.deleted_at) ? `La sucursal ha sido eliminado con éxito` : `La sucursal ha sido activada con éxito`;
		let errorMessage = (!sucursal.deleted_at) ? `La sucursal no se ha podido eliminar` : `La sucursal no se ha podido activar`;
		let btnText = (!sucursal.deleted_at) ? 'Eliminar' : 'Activar';

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

			this.api.sucursales.delete(sucursal.id, reactivate).subscribe(() => {
				this.getSucursales();
				this.layoutUtilsService.showActionNotification(deleteMessage, MessageType.Delete);
			}, () => {
				this.layoutUtilsService.showActionNotification(errorMessage, MessageType.Delete);
			});
		});

	}

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

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

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

}
