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

@Component({
  selector: 'app-resolution-issue-tracking',
  templateUrl: './resolution-issue-tracking.component.html',
  styleUrls: ['./resolution-issue-tracking.component.css']
})
export class ResolutionIssueTrackingComponent {

  public formGroup: FormGroup;
  public isLoading: boolean;

  constructor(
    @Inject(MAT_DIALOG_DATA) public objIssueTracking: GetIssueTracking,
    public resourcesService: ResourcesService,
    private _dialog: MatDialog,
    private _issueTrackingService: IssureTrackingService,
    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.SEPR_IDPR}?`,
      },
      disableClose: true,
    }).afterClosed().subscribe((result) => {
      if (result) {
        this.resolutionIssueTracking();
      }
    })
  }

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

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