import { Component, ElementRef, Inject, OnInit, ViewChild } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { ResourcesService } from '../../../../services/resources.service';
import { EncService } from '../../../../services/enc.service';

@Component({
  selector: 'app-agree-order',
  standalone: false,
  templateUrl: './agree-order.component.html',
  styleUrl: './agree-order.component.css'
})
export class AgreeOrderComponent implements OnInit {
  idOrder: string | null;
  agreeOrder: boolean;
  signatureData: string | null;
  negativeComments: string;

  @ViewChild('pad') pad!: any;

  constructor(
    @Inject(MAT_DIALOG_DATA) private _data: any,
    private _dialogRef: MatDialogRef<AgreeOrderComponent>,
    private _resourcesService: ResourcesService,
    private _encService: EncService,
  ) {
    this.idOrder = null;
    this.agreeOrder = false;
    this.signatureData = null;
    this.negativeComments = "";
  }

  ngOnInit(): void {
    if(this._data.idOrder != null && this._data.idOrder != undefined && this._data.idOrder != ""){
      this.getCorrectiveOrderDetails();
    }else{
      this._resourcesService.openSnackBar("El ID de la orden de mantenimiento correctivo no fue enviado.");
      this._dialogRef.close();
    }
  }

  private async getCorrectiveOrderDetails(){
    this.idOrder = await this._encService.decrypt(this._data.idOrder);
  }

  clearPad(){
    this.pad!.signaturePad.clear();
    this.signatureData = null;
  }

  saveSignature(){
    let signature = this.pad!.signaturePad.toDataURL();
    if(typeof signature == 'string' && signature.length > 0){
      this.signatureData = signature;
      this._resourcesService.openSnackBar("Firma capturada correctamente.");
    }else{
      this._resourcesService.openSnackBar("Error al intentar capturar la firma.");
    }
  }

  changeAgreement(){
    if(this.pad != undefined){
      this.pad.signaturePad.clear();
    }

    this.signatureData = null;
    this.negativeComments = "";
  }

  async saveOrderAction(){
    let data: string[] = [];
    if(this.agreeOrder){
      data.push("A");
      data.push(this.signatureData!);
    }else{
      data.push("R");
      data.push(this.negativeComments);
    }

    let dataStr = JSON.stringify(data);
    let dataEnc = await this._encService.encrypt(dataStr);

    this._dialogRef.close(dataEnc);
  }
}
