import { Component, Inject, OnInit } from '@angular/core';
import { OccupationAreasListItem } from '../../../../interfaces/equipment-management.interface';
import { FormControl, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { EncService } from '../../../../services/enc.service';

@Component({
    selector: 'app-new-occupation',
    templateUrl: './new-occupation.component.html',
    styleUrl: './new-occupation.component.css',
    standalone: false
})
export class NewOccupationComponent implements OnInit {
  occupationAreas: OccupationAreasListItem[];
  areaControl: FormControl;
  descriptionControl: FormControl;

  constructor(
    @Inject(MAT_DIALOG_DATA) private _data: any,
    private _dialogRef: MatDialogRef<NewOccupationComponent>,
    private _encService: EncService,
  ) {
    this.occupationAreas = this._data.occupationAreas;
    this.areaControl = new FormControl('', Validators.required);
    this.descriptionControl = new FormControl('', [Validators.required, Validators.minLength(15), Validators.maxLength(150)]);
  }

  ngOnInit(): void {
    if(this._data.action == 'edit'){
      this.init();
    }
  }

  async init(){
    for(const area of this._data.occupationAreas){
      let codeDec = await this._encService.decrypt(area.CODE);
      let occupationArea = this._data.occupation.OCUPACION.substring(0, 2);
      
      if(codeDec == occupationArea){
        this.descriptionControl.setValue(this._data.occupation.DESCRIPCION);
        this.areaControl.setValue(area.CODE);
        this.areaControl.disable();
      }
    }
  }

  saveOccupation(){
    let data = `${this.areaControl.value}|${this.descriptionControl.value}`;
    
    if(this._data.action == 'edit'){
      data += `|${this._data.occupation.OCUPACION}`;
    }

    this._dialogRef.close(data);
  }
}
