import { Component } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { FormsModule } from '@angular/forms';
import { Router, ActivatedRoute } from '@angular/router';
import { Title } from '@angular/platform-browser';
import { CommonModule } from '@angular/common';

@Component({
  selector: 'account-forgot',
  templateUrl: './forgotpassword.component.html',
  imports: [ FormsModule, CommonModule ]
})
export class ForgotPasswordComponent {
  email: string = "";
  errorMsgs: string[] = [];
  returnURL: string = '/';

  constructor( private http: HttpClient, private router: Router, private route: ActivatedRoute, private title: Title) {
    this.title.setTitle("Forgot Password | Mistox");
    this.route.queryParams.subscribe(params => {
      this.returnURL = params['returnURL'] || '/';
    });
  }

  sleep(ms: number) {
    return new Promise(resolve => setTimeout(resolve, ms));
  }

  onSubmit() {
    // Clear errors
    this.errorMsgs = [];

    // Send to server and wait for response
    this.errorMsgs.push("Waiting for response from server");
    const body = new HttpParams()
        .set("Email", this.email)
    const headers = new HttpHeaders({
        'Content-Type': 'application/x-www-form-urlencoded',
    });
    this.http.post( "api/account/sendresetpassword", body, { headers, responseType: "text"  } ).subscribe({
      next: async (data) => {
          if (data.trim() == "Success"){
            this.errorMsgs = ["Reset-password sent"];
            await this.sleep(3000);
            this.router.navigate([this.returnURL]);
          }else{
            this.errorMsgs = [data];
          }
      },
      error: err => {
          console.log("HTTP Error Signing In: ", err);
      }
  });
  }
}