import {Component, Inject} from '@angular/core';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {EditUsersComponent} from '../../../user/users/edit-users/edit-users.component';
import {Router} from '@angular/router';
import {MAT_DIALOG_DATA, MatDialogRef} from '@angular/material';
import {EditComponent} from '../../../../classes/base_components/edit/edit.component';
import {Product} from '../products.service';
import {Dialog} from '../../../../classes/dialog';
import {setErrors} from '../../../../classes/utils';


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

    /**
     *
     * @param {FormBuilder} fb ye service baray etelaat form
     * @param {Router} router baray navigate hast bein component hay dege
     * @param {Dialog} dialog baray diaog hast
     * @param {MatDialogRef<EditProductComponent>} dialogRef
     * @param data  etelaat dialog
     */
    constructor(private fb: FormBuilder,
                private router: Router,
                protected  dialog: Dialog,
                public  dialogRef: MatDialogRef<EditProductComponent>,
                @Inject(MAT_DIALOG_DATA) data,
    ) {
        super();
        this.product = data;
        this.form = this.fb.group({
            nameCtrl: this.nameCtrl,
            priceCtrl: this.priceCtrl,
        });
    }

    onSubmit() {
        this.loading = true;
        if (!this.form.valid) {
            this.loading = false;
            return;
        }
        this.product.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);
    }
}
