import {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 {FormasPago} from '../formas-pago.model';
import Utils from "../../../../../utils";

@Component({
	selector: 'kt-formas-pago-edit',
	templateUrl: './formas-pago-edit.component.html',
	styleUrls: ['./formas-pago-edit.component.scss']
})
export class FormasPagoEditComponent implements OnInit {

	formaPagoForm: FormGroup;
	selectedTab = 0;
	subscriptions: Subscription[] = [];
	isNewFormaPago = false;
	isLoading = true;
	loading = false;
	formaPagoID = 0;
	data: any;

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

	ngOnInit() {
		this.crearFormulario();
	}

	getFormaPago() {
		let routeSubscription = this.activatedRoute.params.subscribe(params => {
			this.formaPagoID = params.id;
			if (this.formaPagoID && this.formaPagoID > 0) {
				this.isNewFormaPago = false;
				this.api.formasPago.show(this.formaPagoID).subscribe(res => {
					this.isLoading = false;
					res.zeros = Utils.toNumber(res.zeros);
					this.formaPagoForm.reset(res);
					this.ref.detectChanges();
				});
			} else {
				this.isNewFormaPago = true;
				this.isLoading = false;
				this.ref.detectChanges();
			}
		});
		this.subscriptions.push(routeSubscription);
	}

	crearFormulario() {
		this.formaPagoForm = this.fb.group({
			nombre: [null, [Validators.required, Validators.maxLength(128)]],
			zeros: [null, '']
		});
	}

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

		let formaPago: FormasPago = this.formaPagoForm.value as FormasPago;

		if (this.isNewFormaPago) {
			this.addFormaPago(formaPago);
		} else
			this.updateFormaPago(this.formaPagoID, formaPago);
	}

	addFormaPago(formaPago) {
		formaPago.zeros = formaPago.zeros ? '1' : '0'
		this.api.formasPago.create(formaPago).subscribe(() => {
			this.loading = false;
			this.layoutUtilsService.showActionNotification('Forma de pago guardada con éxito.', MessageType.Create);
			this.router.navigate(['../'], {relativeTo: this.activatedRoute})
		}, () => {
			this.loading = false;
		});
	}

	updateFormaPago(id, formaPago) {
		formaPago.zeros == false ? formaPago.zeros = '0' : formaPago.zeros = '1';
		this.api.formasPago.update(id, formaPago).subscribe(() => {
			this.loading = false;
			this.layoutUtilsService.showActionNotification('Forma de pago actualizada con éxito.', MessageType.Update);
			this.router.navigate(['../../'], {relativeTo: this.activatedRoute})
		}, () => {
			this.loading = false;
		});
	}

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

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

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