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-family',
  templateUrl: './new-family.component.html',
  styleUrls: ['./new-family.component.css']
})
export class NewFamilyComponent implements OnInit {
  familyCodeControl: FormControl;
  familyNameControl: FormControl;
  isNew: boolean;

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

  ngOnInit(): void {
    if(this._data.action != 'new'){
      this.familyCodeControl.disable();
      this.familyCodeControl.setValue(this._data.family.CODIGOFAMILIA);
      this.familyNameControl.setValue(this._data.family.NOMBREFAMILIA);
      this.isNew = false;
    }
  }

  validateFamilyCode(value: string){
    this.familyCodeControl.markAsTouched();
    this.familyCodeControl.setValue(value.toUpperCase());
  }

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

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

    let data = `${this.familyCodeControl.value}|${this.familyNameControl.value}`;
    let dataEnc = await this._encService.encrypt(data);
    this._dialofRef.close(dataEnc);
  }
}
