import {AfterViewInit, ChangeDetectorRef, Component, OnInit, ViewRef} from '@angular/core';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {Subscription} from 'rxjs';
import {ActivatedRoute, Router} from '@angular/router';
import {LayoutUtilsService, MessageType} from '../../../../../core/_base/crud';
import {ApiService} from '../../../../../core/api/api.service';
import {MatTableDataSource} from '@angular/material';
import {Usuario} from '../usuarios.model';
import {ConfirmPasswordValidator} from '../../../../../../app/views/pages/auth/register/confirm-password.validator';
import {FiltrosServiciosResponseModel} from '../../../servicios/models/filtros-servicios-response.model';
import {FiltrosUsuariosResponseModel} from '../models/filtros-usuarios-response.model';
import Utils from "../../../../../utils";

@Component({
	selector: 'kt-usuarios-edit',
	templateUrl: './usuarios-edit.component.html',
	styleUrls: ['./usuarios-edit.component.scss']
})
export class UsuariosEditComponent implements OnInit, AfterViewInit {
	//SearchRols
	typingTimerRol;
	typingIntervalRol = 700;
	searchTextRol: string = '';
	lastLengthRol = 0;
	hidePassword = true;
	sucursales;
	tipos_empleados;
	roles;

	dataSourceRoles: MatTableDataSource<any>;

	usuarioForm: FormGroup;
	selectedTab = 0;
	subscriptions: Subscription[] = [];
	isNewUsuario = false;
	isLoading = true;
	loading = false;
	usuarioId = 0;
	imagen;
	rolesObj = [];

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

	ngOnInit() {
		this.crearFormulario();
		this.getFiltros();
	}

	getUsuario() {
		let routeSubscription = this.activatedRoute.params.subscribe(params => {
			this.usuarioId = params.id;
			if (this.usuarioId && this.usuarioId > 0) {
				this.isNewUsuario = false;
				this.api.usuarios.show(this.usuarioId).subscribe(res => {
					this.isLoading = false;
					this.usuarioForm.get('password').clearValidators();
					this.usuarioForm.get('confirmPassword').clearValidators();

					res.role_id = Utils.toNumber(res.role_id);
					res.sucursal_id = Utils.toNumber(res.sucursal_id);
					res.tipo_empleado_id = Utils.toNumber(res.tipo_empleado_id);
					
					this.usuarioForm.reset(res);
					this.dataSourceRoles.data = res.roles;
					this.ref.detectChanges();
				});
			} else {
				this.isNewUsuario = true;
				this.isLoading = false;
				this.ref.detectChanges();
			}
		});
		this.subscriptions.push(routeSubscription);
	}

	crearFormulario() {
		this.usuarioForm = this.fb.group({
			nombre: [null, [Validators.required, Validators.maxLength(128)]],
			apellido_paterno: [null, [Validators.required, Validators.maxLength(128)]],
			apellido_materno: [null, [Validators.required, Validators.maxLength(128)]],
			email: [null, [Validators.required, Validators.email, Validators.maxLength(128)]],
			telefono: [null, [Validators.required, Validators.minLength(10), Validators.maxLength(10)]],
			password: [null, [Validators.required, Validators.maxLength(128), Validators.minLength(5)]],
			confirmPassword: [null, Validators.compose([Validators.required, Validators.minLength(5), Validators.maxLength(128)])],
			sucursal_id: [null, [Validators.required]],
			tipo_empleado_id: [null, [Validators.required]],
			role_id: [null, [Validators.required]],
		}, {
			validator: ConfirmPasswordValidator.MatchPassword
		});	}

	//Busqueda de articulos
	onKeyUpRol(ev) {
		clearTimeout(this.typingTimerRol);
		this.typingTimerRol = setTimeout(() => {
			this.filterRol(ev.target.value)
		}, this.typingIntervalRol);
	}

	onKeyDownRol() {
		clearTimeout(this.typingTimerRol);
	}

	filterRol(filterValue: string,) {
		if (filterValue.length != 0) {
			this.searchTextRol = filterValue.trim().toLowerCase();
			this.searchRol();
		} else if (this.lastLengthRol != 0) {
			this.searchTextRol = '';
			this.searchRol();
			this.ref.detectChanges();
		}

		this.lastLengthRol = filterValue.length;
	}

	searchRol() {
		this.api.usuarios.getRoles('security/roles',this.searchTextRol).subscribe(res => {
			this.rolesObj = res.data;

			setTimeout(() => {
				if (this.ref && !(this.ref as ViewRef).destroyed) {
					this.ref.detectChanges();
				}
			});
		})

	}

	getFiltros(){
		this.api.usuarios.filtrosUsuarios('filtros_usuarios').subscribe((res: FiltrosUsuariosResponseModel) => {
			this.sucursales = res.sucursales;
			this.tipos_empleados = res.tipos_empleados;
			this.roles = res.roles;
			this.ref.detectChanges();
		})
	};

	onFilterSelect(article) {
		let articles = this.dataSourceRoles.data;
		let indice = articles.findIndex(articlee => articlee.id == article.id);
		if (indice == -1) {
			this.dataSourceRoles.data.push(article);
			this.dataSourceRoles._updateChangeSubscription();
		}
		this.usuarioForm.get('rol').setValue('');
	}

	deleteArtcle(article) {
		let articles = this.dataSourceRoles.data;
		let indice = articles.findIndex(articlee => articlee.id == article.id);
		this.dataSourceRoles.data.splice(indice, 1);
		this.dataSourceRoles._updateChangeSubscription();
	}// Fin busqueda de articulos

	onSubmit() {
		let controls = this.usuarioForm.controls;
		if (this.usuarioForm.invalid) {
			Object.keys(controls).forEach(controlName => {
				controls[controlName].markAsTouched();
			})
			return;
		}

		let usuario : Usuario = this.usuarioForm.value as Usuario;

		usuario.roles = this.dataSourceRoles.data;

		if (this.isNewUsuario) {
			this.addUsuario(usuario);
		} else
			this.updateUsuario(this.usuarioId, usuario);
	}

	addUsuario(usuario) {
		this.api.usuarios.create(usuario).subscribe(() => {
			this.loading = false;
			this.layoutUtilsService.showActionNotification('Usuario guardado con éxito.', MessageType.Create);
			this.router.navigate(['../'], {relativeTo: this.activatedRoute})
		}, () => {
			this.loading = false;
		});
	}

	updateUsuario(id, usuario) {
		this.api.usuarios.update(id, usuario).subscribe(() => {
			this.loading = false;
			this.layoutUtilsService.showActionNotification('Usuario actualizado con éxito.', MessageType.Update);
			this.router.navigate(['../../'], {relativeTo: this.activatedRoute})
		}, () => {
			this.loading = false;
		});
	}

	isControlValid(controlName: string): boolean {
		let control = this.usuarioForm.controls[controlName];
		if (!control) {
			return false;
		} else if (control.valid) {
			return false;
		}
		return true;
	}

	isControlHasError(controlName: string, validationType: string): boolean {
		let control = this.usuarioForm.controls[controlName];
		if (!control) {
			return false;
		}
		return control.hasError(validationType) && (control.dirty || control.touched);
	}

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