import { Component, OnInit } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';
import { ResourcesService } from '../../../../../services/resources.service';
import { MatDialogRef } from '@angular/material/dialog';
import { EncService } from '../../../../../services/enc.service';

@Component({
    selector: 'app-other-specialties-dialog',
    templateUrl: './other-specialties-dialog.component.html',
    styleUrl: './other-specialties-dialog.component.css',
    standalone: false
})
export class OtherSpecialtiesDialogComponent implements OnInit {
  customSpecialties: string[];
  specialtyControl: FormControl;

  constructor(
    private _resourcesService: ResourcesService,
    private _dialogRef: MatDialogRef<OtherSpecialtiesDialogComponent>,
    private _encService: EncService,
  ) {
    this.customSpecialties = [];
    this.specialtyControl = new FormControl('', Validators.maxLength(100));
  }

  ngOnInit(): void {
    
  }

  addSpecialtyToList(){
    if(this.specialtyControl.value != undefined && this.specialtyControl.value != null && this.specialtyControl.value != ''){
      let specialtyFilt = this.customSpecialties.filter(item => item == this.specialtyControl.value);

      if(specialtyFilt.length > 0){
        this._resourcesService.openSnackBar(`La especialidad ${this.specialtyControl.value} ya está agregada.`);
      }else{
        this.customSpecialties.push(this.specialtyControl.value);
      }

      this.specialtyControl.setValue(null);
    }
  }

  deleteSpecialty(specialty: string){
    let specialtiesAux: string[] = [];
    for(const specialtyStr of this.customSpecialties){
      if(specialty != specialtyStr){
        specialtiesAux.push(specialtyStr);
      }
    }

    this.customSpecialties = specialtiesAux;
  }

  async closeDialog(){
    if(this.customSpecialties.length > 0){
      let specialtiesStr = JSON.stringify(this.customSpecialties);
      let specialtiesEnc = await this._encService.encrypt(specialtiesStr);

      this._dialogRef.close(specialtiesEnc);
    }else{
      this._resourcesService.openSnackBar('Aún no se han agregado especialidades.');
    }
  }
}
