import { Component, Inject, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { ConditionData, DataDialogCondition } from 'src/app/interfaces/acquisition-management/provider.interface';

@Component({
  selector: 'app-info-condition-provider',
  templateUrl: './condition-provider-form.component.html',
  styleUrls: ['./condition-provider-form.component.css']
})
export class ConditionProviderFormComponent implements OnInit {

  public formGroup: FormGroup;
  public titleDialog: string;
  public isLoading: boolean;
  public isLoadingForm: boolean;
  constructor(
    @Inject(MAT_DIALOG_DATA) public dataDialog: DataDialogCondition,
    private _dialogRef: MatDialogRef<ConditionData>
  ) {
    if (dataDialog.typeDialog === 'REGISTER') {
      this.titleDialog = 'Registro de Condición';
    } else if (dataDialog.typeDialog === 'UPDATE') {
      this.titleDialog = 'Modificación de Condición';
    }else{
      this.titleDialog = 'Condición';
    }
    this.isLoading = false;
    this.isLoadingForm = false;
    this.formGroup = this.createFromGroup();
  }

  ngOnInit(): void {
    this.setDataForm();
  }

  private setDataForm() {
    if (this.dataDialog.typeDialog === 'UPDATE' || this.dataDialog.typeDialog === 'ONLYREAD') {
      this.isLoading = true;
      this.formGroup.controls['ID_CONDICION'].setValue(this.dataDialog.dataElement.ID_CONDICION);
      this.formGroup.controls['TIPO_CONDICION'].setValue(this.dataDialog.dataElement.TIPO_CONDICION);
      this.formGroup.controls['INFORMACION'].setValue(this.dataDialog.dataElement.INFORMACION);
      if (this.dataDialog.dataElement.ESTADO !== 'Nuevo') {
        this.formGroup.controls['ESTADO'].setValue('Modificado');
      }
      this.isLoading = false;
    }
  }

  private createFromGroup(): FormGroup {
    return new FormGroup({
      ID_CONDICION: new FormControl(this.dataDialog.dataSource.length + 1, Validators.required),
      TIPO_CONDICION: new FormControl('', Validators.required),
      INFORMACION: new FormControl('', Validators.required),
      ESTADO: new FormControl('Nuevo', Validators.required),
    });
  }

  public registerCondition() {
    this.isLoadingForm = true;
    let arrDataSource: Array<ConditionData> = this.dataDialog.dataSource;
    arrDataSource.push(this.formGroup.value);
    this._dialogRef.close(arrDataSource);
    this.isLoadingForm = false;
  }
  public updateCondition() {
    this.isLoadingForm = true;  
    let arrDataSource: Array<ConditionData> = this.dataDialog.dataSource;
    arrDataSource = arrDataSource.map((element: ConditionData) => {
      if (element.ID_CONDICION === this.formGroup.controls['ID_CONDICION'].value) {
        element = this.formGroup.value;
      }
      return element;
    });
    this._dialogRef.close(arrDataSource);
    this.isLoadingForm = false;
  }

}
