import {AfterViewInit, ChangeDetectorRef, Component, OnInit} from '@angular/core';
import {FormBuilder, 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 {Rol} from '../roles.model';

@Component({
	selector: 'kt-roles-edit',
	templateUrl: './roles-edit.component.html',
	styleUrls: ['./roles-edit.component.scss']
})
export class RolesEditComponent implements OnInit, AfterViewInit {
	//Forms
	rolForm: FormGroup;
	selectedTab = 0;
	subscriptions: Subscription[] = [];

	isNewRol = true;
	isLoading = true;
	rolId = 0;
	loading = false;
	permissions = [];

	constructor(private fb: FormBuilder,
				private router: Router,
				private layoutUtilsService: LayoutUtilsService,
				private activatedRoute: ActivatedRoute,
				private ref: ChangeDetectorRef,
				private api: ApiService) {
	}

	ngOnInit() {
		this.crearFormulario();
	}

	getPermisos() {
		this.api.roles.getPermisos().subscribe(res => {
			for (let key in res.permissions) {
				this.permissions.push({name: key, value: res[key]});
			}
			this.ref.detectChanges();
		})
	}

	crearFormulario() {
		this.rolForm = this.fb.group({
			name: [null, [Validators.required, Validators.maxLength(128)]],
			slug: [null, [Validators.required, Validators.maxLength(128)]],
			web: [false, [Validators.required]],
			movil: [false, [Validators.required]]
		})
	}

	getRol() {
		let routeSubscription = this.activatedRoute.params.subscribe(params => {
			this.rolId = params.id;
			if (this.rolId && this.rolId > 0) {
				this.isNewRol = false;
				this.api.roles.show(this.rolId)
					.subscribe(res => {
						this.isLoading = false;
						res.web = res.web == '1' || res.web == 1;
						res.movil = res.movil == '1' || res.movil == 1;
						this.rolForm.reset(res);
						for (let key in res.permissions) {
							this.permissions.push({name: key, value: res.permissions[key]});
						}
						this.ref.detectChanges();
					});
			} else {
				this.getPermisos();
				this.isNewRol = true;
				this.isLoading = false;
				this.ref.detectChanges();
			}
		});
		this.subscriptions.push(routeSubscription);
	}

	prepararRol() {
		let rol: Rol = this.rolForm.value as Rol;

		let obj = {};

		this.permissions.forEach((v, i) => {
			obj[v.name] = v.value;
		});

		rol.permissions = obj;

		return rol;
	}

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

		let rol = this.prepararRol();
		if (this.isNewRol) {
			this.addRol(rol);
		} else
			this.updateRol(this.rolId, rol);
	}

	addRol(rol) {
		this.api.roles.create(rol).subscribe(() => {
			this.loading = false;
			this.layoutUtilsService.showActionNotification('Rol guardado con éxito.', MessageType.Update);
			this.router.navigate(['../'], {relativeTo: this.activatedRoute})
		}, () => {
			this.loading = false;
		});
	}

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

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

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

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