import { HttpErrorResponse } from '@angular/common/http';
import { Component, Inject, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { MatDialog, MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { lastValueFrom } from 'rxjs';
import { AlertComponent } from 'src/app/components/resources/dialogs/alert/alert.component';
import { ResponseDataWorkteam, DialogModule, Workteam } from 'src/app/interfaces/personal-managment/workteam.interface';
import { ResponseData } from 'src/app/interfaces/response-data';
import { WorkTeamService } from 'src/app/services/personal-management/work-team.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';

@Component({
  selector: 'app-work-team-form',
  templateUrl: './work-team-form.component.html',
  styleUrls: ['./work-team-form.component.css']
})
export class WorkTeamFormComponent implements OnInit {


  public isLoading: boolean;
  public formGroup: FormGroup;
  public idWorkteam: string;
  public enable: string;

  constructor(
    private _resourcesService: ResourcesService,
    private _dialog: MatDialog,
    private _workteamService: WorkTeamService,
    private dialogRef: MatDialogRef<WorkTeamFormComponent>,
    @Inject(MAT_DIALOG_DATA) public dialogData: DialogModule
  ) {
    this.isLoading = false;
    this.idWorkteam = "";
    this.enable = "";
    this.formGroup = this.createFormGroup();
  }

  ngOnInit(): void {
    if (this.dialogData.action != "REG") {
      this.idWorkteam = this.dialogData.dataElement.WORKTEAM_ID;
      this.getData();
    }
    this.enable = this.dialogData.action == "DET" ? "0" : "1";
  }

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

  public alert(typeForm: string) {
    if (typeForm === 'REG') {
      this._dialog.open(AlertComponent, {
        data: {
          title: 'Registrar Equipo de Trabajo',
          description: '¿Está seguro que desea registrar al equipo?',
          icon: 'warning',
        },
        disableClose: true,
      }).afterClosed().subscribe((result) => {
        if (result) {
          this.storeWorkteam();
        }
      });
    } else {
      this._dialog.open(AlertComponent, {
        data: {
          title: 'Actualizar Equipo de Trabajo',
          description: '¿Está seguro que desea actualizar al equipo?',
          icon: 'warning',
        },
        disableClose: true,
      }).afterClosed().subscribe((result) => {
        if (result) {
          this.updateWorkteam();
        }
      });
    }
  }

  private async storeWorkteam(){
    await lastValueFrom(this._workteamService.storeWorkteam(await this.workteamObject())).then(
      (responseData: ResponseData) => {
        this._resourcesService.openSnackBar("Creación Exitosa!");
        this.dialogRef.close(true);
      }, (error: HttpErrorResponse) => this._resourcesService.checkErrors(error)
    );
  }

  private async updateWorkteam(){
    await lastValueFrom(this._workteamService.updateWorkteam(await this.workteamObject())).then(
      (responseData: ResponseData) => {
        this._resourcesService.openSnackBar("Actualización Exitosa!");
        this.dialogRef.close(true);
      }, (error: HttpErrorResponse) => this._resourcesService.checkErrors(error)
    );
  }

  private async workteamObject(): Promise<Workteam> {
    return {
      WORKTEAM_ID: this.idWorkteam,
      NAME: this.name.value == null ? null : this.name.value.trim(),
      SPECIALITY: this.speciality.value == null ? null : this.speciality.value.trim(),
      SAVED_BY_USER: this._resourcesService.getUser(),
      LINE_NUMBER: 1
    }
  }

  private async putDataOnForm(workteam: Workteam) {
    this.name.setValue(workteam.NAME)
    this.speciality.setValue(workteam.SPECIALITY)
  }

  private async getData() {
    this.isLoading = true;
    await lastValueFrom(this._workteamService.getWorkteamById(this.idWorkteam)).then(
      (responseData: ResponseDataWorkteam) => {
        this.putDataOnForm(responseData.response);
        this.isLoading = false;
      }, (error: HttpErrorResponse) => this._resourcesService.checkErrors(error)
    );
  }

  get name() {
    return this.formGroup.get('name')!;
  }

  get speciality() {
    return this.formGroup.get('speciality')!;
  }

}
