// Angular Core
import { HttpErrorResponse } from '@angular/common/http';
import { Component, EventEmitter, OnInit, Output } from '@angular/core';

// RxJs
import { catchError, throwError } from 'rxjs';

// Services
import { AccountInfoService } from 'src/app/services/accountInfo/account-info.service';
import { environment } from 'src/environments/environment';

@Component({
  standalone: false,
  selector: 'app-captcha',
  templateUrl: './captcha.component.html',
  styleUrls: ['./captcha.component.scss']
})
export class CaptchaComponent implements OnInit {

  @Output() captchaInput = new EventEmitter<string>();
  @Output() captcha = new EventEmitter<string>();
  imgUrl: string = environment.imageUrl;
  
  constructor(
    private accountInfo: AccountInfoService
  ) { }

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

  captchaToDisplay!: string;

  getCaptchaData(event:any){
    this.captchaInput.emit(event.target.value);
  }

  /**
   * Method introduced as part of TRX-6404
   * Method to get captcha
   *
   * @returns void
  */
  getCaptcha() {
    this.accountInfo.getCaptcha()
      .pipe(
        catchError(() => {
          return throwError(() => new Error('ups sommething happend'));
        })
      )
      .subscribe({
        next: (res: any) => {
          this.captchaToDisplay = res.data.captcha;
          this.captcha.emit(this.captchaToDisplay);
        },
        error: (err: HttpErrorResponse) => {
          this.accountInfo.errorCallBack(err);
        },
        complete: () => { }
      });
  }
}
