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 {Dialog} from '../../../../classes/dialog';
import {Service, ServicesService} from '../services.service';
import {TypesService} from '../../types/types.service';
import {setErrors} from '../../../../classes/utils';


@Component({
  selector: 'app-edit-product',
  templateUrl: './edit-services.component.html',
  styleUrls: ['./edit-services.component.scss']
})
export class EditServicesComponent extends EditComponent {
  public loading = false;
  types;
  nameCtrl = new FormControl('', [Validators.required]);
  priceCtrl = new FormControl('', [Validators.required]);
  typesCtrl = new FormControl('', [Validators.required]);
  productCtrl = new FormControl('', [Validators.required]);
  service: Service;
  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 typeservice: TypesService,
    private  serviceservices: ServicesService,
    private fb: FormBuilder,
    private router: Router,
    protected  dialog: Dialog,
    public  dialogRef: MatDialogRef<EditServicesComponent>,
    @Inject(MAT_DIALOG_DATA) data,
  ) {
    super();
    const basics = JSON.parse(localStorage.getItem('basics'));
    this.types = basics['types'];
    this.service = data;
    this.form = this.fb.group({
      nameCtrl: this.nameCtrl,
      priceCtrl: this.priceCtrl,
      typesCtrl: this.typesCtrl,
      productCtrl: this.productCtrl,
    });
  }

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

