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

@Component({
  selector: 'app-new-occupation',
  templateUrl: './new-occupation.component.html',
  styleUrls: ['./new-occupation.component.css']
})
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);
  }
}
