import { Component, Inject, OnInit } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { MatSnackBar } from '@angular/material/snack-bar';
import { Router } from '@angular/router';
import { lastValueFrom } from 'rxjs';
import { GETBFOService } from 'src/app/services/getb/getbfo/getbfo.service';

@Component({
  selector: 'app-getbfo-saveform',
  templateUrl: './getbfo-saveform.component.html',
  styleUrls: ['./getbfo-saveform.component.css']
})
export class GETBFOSAVEFORMComponent implements OnInit {

  primary_key: string = "";
  constructor(
    private _formService: GETBFOService,
    private _snackBar: MatSnackBar,
    private _router:Router,
    public dialogRef: MatDialogRef<GETBFOSAVEFORMComponent>,
    @Inject(MAT_DIALOG_DATA) public data: any,
  ) { }

  ngOnInit(): void {
  }

  public getPosibilityId():Array<any>{
    let arrFormId: Array<any> = [];
    for (let index0 = 0; index0 < this.data.fields.length; index0++) {
      if (!this.data.fields[index0].multi_data) {
        for (let index1 = 0; index1 < this.data.fields[index0].form.length; index1++) {
          if(this.data.fields[index0].form[index1] === 'input' || this.data.fields[index0].form[index1] !== 'textarea' || this.data.fields[index0].form[index1] === 'select'){
            if (this.data.fields[index0].form[index1].required) {
              arrFormId.push(this.data.fields[index0].form[index1]);
            }
          }
        }
      }
    }
    return arrFormId;
  }

  public async saveJson(){
    this.data.primary_key = this.primary_key;
    await lastValueFrom(this._formService.createForm(this.data)).then((data:ResponseData) => {
      if (!data.error) {
        this.openSnackBar("¡Registro de formulario exitoso!");
        this._router.navigate(['sam/getbfo']);
      }else{
        this.openSnackBar(data.msg);
      }
    }, error => {
      console.log(error);
    });
  }

  private openSnackBar(
    message: string,
    duration: number = 4000,
    action: string = 'Cerrar'
  ) {
    this._snackBar.open(message, action, {
      duration: duration,
    });
  }

}

export interface ResponseData{
  error: boolean;
  msg: string;
  response: Array<any>;
}
