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

@Component({
  selector: 'app-new-subfamily',
  templateUrl: './new-subfamily.component.html',
  styleUrls: ['./new-subfamily.component.css']
})
export class NewSubfamilyComponent implements OnInit {
  familyCodeControl: FormControl;
  subfamilyCodeControl: FormControl;
  subfamilyNameControl: FormControl;
  isNew: boolean;

  constructor(
    @Inject(MAT_DIALOG_DATA) private _data: any,
    private _encService: EncService,
    private _dialogRef: MatDialogRef<NewSubfamilyComponent>,
    private _resourcesService: ResourcesService,
  ) {
    this.familyCodeControl = new FormControl({disabled: true, value: ''}, Validators.required);
    this.subfamilyCodeControl = new FormControl('', [Validators.required, Validators.maxLength(5)]);
    this.subfamilyNameControl = new FormControl('', [Validators.required, Validators.maxLength(50)]);
    this.isNew = true;
  }

  ngOnInit(): void {
    this.init();
  }

  async init(){
    let familyCodeDec = await this._encService.decrypt(this._data.family);
    this.familyCodeControl.setValue(familyCodeDec);

    if(this._data.action != 'new'){
      this.isNew = false;
      let subfamilyCodeDec = await this._encService.decrypt(this._data.subfamily.CODIGOSUBFAMILIA);

      this.subfamilyCodeControl.disable();
      this.subfamilyCodeControl.setValue(subfamilyCodeDec);
      this.subfamilyNameControl.setValue(this._data.subfamily.NOMBRESUBFAMILIA);
    }
  }

  async saveSubfamily(){
    if(this.familyCodeControl.invalid){
      this._resourcesService.openSnackBar('El código de la familia relacionada es inválido.');
      return;
    }

    if(this.subfamilyCodeControl.invalid){
      this._resourcesService.openSnackBar('El código de la subfamilia es inválido.');
      return;
    }

    if(this.subfamilyNameControl.invalid){
      this._resourcesService.openSnackBar('El nombre de la subfamilia es inválido.');
      return;
    }

    let subfamilyCode = await this._encService.encrypt(this.subfamilyCodeControl.value);
    let data = `${this._data.family}|${subfamilyCode}|${this.subfamilyNameControl.value}`;
    let dataEnc = await this._encService.encrypt(data);

    this._dialogRef.close(dataEnc);
  }

  verifySubfamilyCode(value: string){
    this.subfamilyCodeControl.setValue(value.toUpperCase());
    this.subfamilyCodeControl.markAsTouched();
  }
}
