import {Component, Inject} from '@angular/core';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {Router} from '@angular/router';
import {MAT_DIALOG_DATA, MatDialogRef} from '@angular/material';
import {EditComponent} from '../../../../classes/base_components/edit/edit.component';
import {setErrors} from '../../../../classes/utils';
import {Dialog} from '../../../../classes/base_components/dialog/dialog';
import {Type} from '../../../../classes/resorcess/types.service';


@Component({
    selector: 'app-edit-product',
    templateUrl: './edit-types.component.html',
    styleUrls: ['./edit-types.component.scss']
})
export class EditTypesComponent extends EditComponent {
    public loading = false;
    nameCtrl = new FormControl('', [Validators.required]);
    type: Type;
    form: FormGroup;

    constructor(private fb: FormBuilder,
                private router: Router,
                protected  dialog: Dialog,
                public  dialogRef: MatDialogRef<EditTypesComponent>,
                @Inject(MAT_DIALOG_DATA) data,
    ) {
        super();
        this.type = data;
        this.form = this.fb.group({
            nameCtrl: this.nameCtrl,

        });

    }

    onSubmit() {
        this.loading = true;
        if (!this.form.valid) {
            this.loading = false;
            return;
        }
        this.type.save({},
            () => {
                this.loading = false;
                this.close();
            },
            (error) => {
                this.loading = false;
                const JsonV = error.errors;
                setErrors(JsonV , this.form.controls, this.dialog);
            });
    }

    close() {
        this.dialogRef.close(true);
    }
}
