import { HttpErrorResponse } from '@angular/common/http';
import { Component, Inject, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import { lastValueFrom } from 'rxjs';
import { DialogDataGroup, GroupRequestLine } from 'src/app/interfaces/acquisition-management/order.interface';
import { DispatchData, ResponseDataDispatch } from 'src/app/interfaces/acquisition-management/dispatch.interface';
import { DispatchService } from 'src/app/services/acquisition-management/dispatch.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';

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

  public formGroup: FormGroup;
  public isLoadingForm: boolean;
  public arrDispatch: Array<DispatchData>;

  constructor(
    @Inject(MAT_DIALOG_DATA) public elementData: DialogDataGroup,
    public resourcesService: ResourcesService,
  ) {
    this.formGroup = this.createFormGroup();
    this.isLoadingForm = false;
    this.arrDispatch = elementData.dispatch;
  }


  ngOnInit(): void {
    this.setDataValue()
  }

  private setDataValue() {
    this.despacho.setValue(this.elementData.dataConfig.DESPACHO);
    this.proposito.setValue(this.elementData.dataConfig.PROPOSITO);
    this.actividad.setValue(this.elementData.dataConfig.ACTIVIDAD)
    this.proyecto.setValue(this.elementData.dataConfig.PROYECTO)

  }

  private createFormGroup(){
    return new FormGroup({
      despacho: new FormControl('', Validators.required),
      proposito: new FormControl('', Validators.required),
      actividad: new FormControl(''),
      proyecto: new FormControl(''),
    });
  }

  public changePurpose() {
    let purpose:string = this.proposito.value;
    if (purpose === 'Actividad') {
      this.actividad.setValidators(Validators.required);
      this.proyecto.clearValidators();
    }else if (purpose === 'Proyecto') {
      this.proyecto.setValidators(Validators.required);
      this.actividad.clearValidators();
    }else if(purpose === 'No Aplica'){
      this.proyecto.clearValidators();
      this.actividad.clearValidators();
    }
    this.proyecto.updateValueAndValidity();
    this.actividad.updateValueAndValidity();
  }

  get despacho() { return this.formGroup.get('despacho')!; }
  get proposito() { return this.formGroup.get('proposito')!; }
  get actividad() { return this.formGroup.get('actividad')!; }
  get proyecto() { return this.formGroup.get('proyecto')!; }

}
