// Angular Core
import { Component, EventEmitter, Input, OnDestroy, OnInit, Output } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { Router } from '@angular/router';

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

// Services
import { PasswordService } from '../../../services/password/password.service';
import { environment } from 'src/environments/environment';

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

  @Output()authenticateEmitter = new EventEmitter<boolean>();
  @Input() authenticate = false;
  fpForm: any = FormGroup ;
  showMsg: boolean = false;
  errorMessage: string = '';
  imgUrl: string = environment.imageUrl;

  constructor(private formBuilder: FormBuilder, private passwordService: PasswordService, private router: Router) { }

  ngOnInit(): void {

    this.fpForm = this.formBuilder.group({
      user_name: ['', Validators.required],
      user_email: ['', Validators.required],
    });

  }

  get fpFormData() { return this.fpForm.controls; }

  /**
   *  method for authentication of user and to send mail to user with temporary password
   */
  getPasswordAuthenticationSubscribe!:Subscription;
  retrievePasswordSubmit() {
    
    if(this.fpForm.invalid){
      return;
    }

    let userName = this.fpFormData.user_name.value ?? '';
    let email = this.fpFormData.user_email.value ?? '';

    this.passwordService.setdeaName(userName);
    this.passwordService.setuserId(email);

    this.getPasswordAuthenticationSubscribe = this.passwordService.getPasswordAuthentication(userName, email)
      .pipe(
        catchError((err) => {
          this.showMsg = true;
          let errorMsg = err.error.feedback;
          errorMsg.forEach((msg: any) => {
            if (msg.code === 'UNKNOWN') {
              this.errorMessage = 'The information you entered is not recognized. Please try again.';
            }
            if (msg.code === 'SUSPENDED') {
              this.errorMessage = 'Your account is suspended. Password reset is unavailable.';
            }
          });
          return throwError(() => new Error('ups sommething happend'));
        })
      )
      .subscribe({
        next: () => {
          this.authenticate = true;
          this.authenticateEmitter.emit(this.authenticate);
        },
        error: (err: any) => {
          this.showMsg = true;
          let errorMsg = err.error.feedback;
          errorMsg.forEach((msg: any) => {
            if (msg.code === 'UNKNOWN') {
              this.errorMessage = 'The information you entered is not recognized. Please try again.';
            }
            if (msg.code === 'SUSPENDED') {
              this.errorMessage = 'Your account is suspended. Password reset is unavailable.';
            }
          });
        },
        complete: () => { }
      });
  };

  ngOnDestroy(){
    this.getPasswordAuthenticationSubscribe?.unsubscribe();
  }

}
