import {Component, Input, OnDestroy, OnInit} from '@angular/core';
import {ActivatedRoute, Router} from "@angular/router";
import {FormService} from "../../services/form.service";
import {Subscription} from "rxjs";
import {Form} from "../../models/Form";
import {UtilsService} from "../../services/utils.service";
import {MessageService} from "primeng/api";
import {TranslateService} from "@ngx-translate/core";
import {DynamicDialogConfig} from "primeng/dynamicdialog";
import {ValidationService} from "../../services/validation.service";

@Component({
    selector: 'app-form',
    templateUrl: './form.component.html',
    styleUrls: ['./form.component.css']
})
export class FormComponent implements OnInit, OnDestroy {
    @Input() code?: string;
    loaded: boolean = false;
    loading: boolean = true;
    saving: boolean = false;

    form?: Form;
    subscriptions: Subscription[] = [];
    errorMessages: any[] =[];

    constructor(
        private activatedRoute: ActivatedRoute,
        private router: Router,
        private formService: FormService,
        private utils: UtilsService,
        private messageService: MessageService,
        private translate: TranslateService,
        public dialogConfig: DynamicDialogConfig,
        public validation: ValidationService
    ) { }

    ngOnDestroy() {
        for (const subscription of this.subscriptions)
            if (subscription)
                subscription.unsubscribe();
        this.subscriptions = [];
    }

    ngOnInit(): void {
        this.initFormCode();
        this.loading = true;
        this.subscriptions.push(
            this.formService.getForm(this.code).subscribe(result => {
                this.form = result;
                this.loaded = true;
                this.loading = false;
                this.initFormData();
            }, error => {
                this.loaded = true;
                this.loading = false;
            })
        );
    }

    initFormCode() {
        if (this.dialogConfig.data && this.dialogConfig.data.code)
            this.code = this.dialogConfig.data.code;
        else
            this.code = this.activatedRoute.snapshot.params["code"];
    }

    initFormData() {
        if (this.dialogConfig.data && this.dialogConfig.data.row) {
            this.form?.fields?.forEach(col => col.value = col.name? this.dialogConfig.data.row[col.name] : null)
            this.form!.id = this.dialogConfig.data.id;
        }
    }

    submit() {
        const validators = this.form?.fields?.filter(o => o.required).map(o =>  {
            return {
                value: o.value,
                validators: [ValidationService.notEmpty],
                name: o.descriptionShort
            }
        }) || [];

        this.errorMessages = this.validation.validate(validators);

        if (!this.errorMessages || this.errorMessages.length < 1) {
            this.saving = true;

            this.formService.postForm(this.form).subscribe(result => {
                if (result) {
                    this.form?.fields?.forEach(o => o.value = null);
                    this.translate.get("FORM.SAVE_SUCCESS").subscribe(value =>
                        this.utils.showInfoMessage(value)
                    );
                }
                this.saving = false;
            }, error => this.saving = false)
        }

    }
}

