import { Component, Inject } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialog, MatDialogRef } from '@angular/material/dialog';
import { FormResolutionIssueTracking, GetIssueTracking } from '../../../../../interfaces/acquisition-management/issue-tracking.interface';
import { ResourcesService, ResponseData } from '../../../../../services/resources.service';
import { DispatchService } from '../../../../../services/acquisition-management/dispatch.service';
import { EncService } from '../../../../../services/enc.service';
import { AlertComponent } from '../../../../resources/dialogs/alert/alert.component';
import { lastValueFrom } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';

@Component({
    selector: 'app-resolution-issue-tracking',
    templateUrl: './resolution-issue-tracking.component.html',
    styleUrl: './resolution-issue-tracking.component.css',
    standalone: false
})
export class ResolutionIssueTrackingComponent {
  public formGroup: FormGroup;
  public isLoading: boolean;

  constructor(
    @Inject(MAT_DIALOG_DATA) public objIssueTracking: GetIssueTracking,
    public resourcesService: ResourcesService,
    private _dialog: MatDialog,
    private _dispatchService: DispatchService,
    private _dialogRef: MatDialogRef<any>,
    private _encService: EncService,
  ) {
    this.formGroup = this.createFormGroup();
    this.isLoading = false;
  }

  private createFormGroup() {
    return new FormGroup({
      DESCRIPCION: new FormControl('', Validators.required),
    });
  }

  public alert() {
    this._dialog.open(AlertComponent, {
      data: {
        icon: 'warning',
        title: 'Confirmación',
        description: `¿Está seguro de dar resolución al problema con el número de seguimiento ${this.objIssueTracking.ID_PROBLEMA}?`,
      },
      disableClose: true,
    }).afterClosed().subscribe((result) => {
      if (result) {
        this.resolutionIssueTracking();
      }
    })
  }

  private async resolutionIssueTracking() {
    this.isLoading = true;
    const objectResult:FormResolutionIssueTracking = await this.createObjectResult();
    await lastValueFrom(this._dispatchService.resolutionIssueTracking(objectResult)).then(
      (responseData: ResponseData) => {
        if (!responseData.error) {
          this.resourcesService.openSnackBar(`El seguimiento del problema con el número ${this.objIssueTracking.ID_PROBLEMA} fue cerrado correctamente.`);
          this._dialogRef.close(true);
        } else {
          this.resourcesService.openSnackBar(responseData.msg)
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.resolutionIssueTracking();
        }
      }
    );
    this.isLoading = false;
  }

  private async createObjectResult() : Promise<FormResolutionIssueTracking>{
    return {
      NUMERO_SEGUIMIENTO:  await this._encService.encrypt(this.objIssueTracking.ID_PROBLEMA.toString()),
      DESCRIPCION: this.formGroup.controls['DESCRIPCION'].value.trim(),
      NUMERO_LINEA: this.resourcesService.getLineNumber(),
      USUARIO: this.resourcesService.getUser(),
    }
  }
}
