import { HttpErrorResponse } from '@angular/common/http';
import { Component, Inject, OnInit } from '@angular/core';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { lastValueFrom } from 'rxjs';
import { DataFields, ResponseDataForm, FormItems, ResponseInformation } from 'src/app/interfaces/dynamic/dynamic-form.interface';
import { ResponseData } from 'src/app/interfaces/response-data';
import { EncService } from 'src/app/services/enc/enc.service';
import { GenericService } from 'src/app/services/forms-management/generic/generic.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';

@Component({
  selector: 'app-failure-form',
  templateUrl: './failure-form.component.html',
  styleUrls: ['./failure-form.component.css']
})
export class FailureFormComponent implements OnInit {
  public isLoading: boolean;
  public numberForm: string;
  public arrFields: Array<DataFields>;
  public titleForm: string;

  constructor(
    public resourcesService: ResourcesService,
    public dialog: MatDialog,
    private _encService: EncService,
    private _dialogRef: MatDialogRef<any>,
    private _genericService: GenericService,
    @Inject(MAT_DIALOG_DATA) public dialogData: DialogModule
  ) {
    this.isLoading = false;
    this.numberForm = '0000000004';
    this.titleForm = '';
    this.arrFields = [];
    this.getDynamicForm();
  }

  ngOnInit(): void {
  }

  private async getDynamicForm() {
    this.isLoading = true;
    await lastValueFrom(this._genericService.generateForm(this.numberForm)).then(
      (responseData: ResponseDataForm) => {
        this.arrFields = responseData.response.FIELDS;
        if (this.dialogData.action === 'UPD') {
          this.setDataFormUpdate();
          this.titleForm = responseData.response.TITULO_MODIFICACION;
        }else {
          this.titleForm = responseData.response.TITULO_REGISTRO;
        }
      }, (error:HttpErrorResponse) => {
        this._dialogRef.close('CLOSE');
        this.resourcesService.checkErrors(error)
      }
    );
    this.isLoading = false;
  }

  private async setDataFormUpdate() {
    this.arrFields = this.arrFields.map((fieldsForm:DataFields) => {
      fieldsForm.form = fieldsForm.form.map((formData:FormItems) => {
        let column:string = formData.column;
        if (formData.data_table.table !== 'NA') {
          formData.value = this.dialogData.dataElement[column] === null ? '' : this.dialogData.dataElement[column];
        }else{

          let infoExtra = column.substring(0,5) + 'INEX';
          let jsonForm = JSON.parse(this.dialogData.dataElement[infoExtra]);
          formData.value = jsonForm !== null ? jsonForm[column] : '';
        }
        return formData;
      })
      return fieldsForm;
    });
  }

  public getInformation(dataInformation: string | Array<ResponseInformation>) {
    if (dataInformation === 'CLOSE') {
      this._dialogRef.close('CLOSE');
    } else if (typeof dataInformation !== 'string' && this.dialogData.action === 'REG'){
      this.registerDynamicForm(dataInformation);
    } else if (typeof dataInformation !== 'string' && this.dialogData.action === 'UPD'){
      this.updateDynamicForm(dataInformation);
    }
  }

  private async registerDynamicForm(dataValue: Array<ResponseInformation>) {
    await lastValueFrom(this._genericService.registerData({
      CODIGO_FORM: await this._encService.encriptar(this.numberForm),
      DATA_VALUE: JSON.stringify(dataValue),
      USER: this.resourcesService.getUser(),
      LINE: '1',
    })).then((responseData: ResponseData) => {
      this.resourcesService.openSnackBar('¡Registro Exitoso!');
      this._dialogRef.close('EXITO');
    }, (error: HttpErrorResponse) => this.resourcesService.checkErrors(error))
  }

  private async updateDynamicForm(dataValue: Array<ResponseInformation>) {
    await lastValueFrom(this._genericService.updateData({
      CODIGO_FORM: await this._encService.encriptar(this.numberForm),
      DATA_VALUE: JSON.stringify(dataValue),
      USER: this.resourcesService.getUser(),
      LINE: '1',
    })).then((responseData: ResponseData) => {
      this.resourcesService.openSnackBar('¡Modificación Exitosa!');
      this._dialogRef.close('EXITO');
    }, (error: HttpErrorResponse) => this.resourcesService.checkErrors(error))
  }
}

export interface DialogModule {
  title: string;
  action: string;
  dataElement: any;
}
