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-reset',
  templateUrl: './resetpassword.component.html',
  imports: [ FormsModule, CommonModule ]
})
export class ResetPasswordComponent {
  
  UserName: string = "";
  ResetPwd: string = "";
  Password: string = "";
  PassworR: string = "";

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

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

  onSubmit() {
    if (this.Password != this.PassworR){
      this.errorMsgs.push("Passwords must match");
    }
    if (this.Password.length < 6){
      this.errorMsgs.push("Password must be at least 6 Characters long");
    }
    if (this.errorMsgs.length == 0){
      // Send to server and wait for response
      this.errorMsgs.push("Waiting for response from server");
      const body = new HttpParams()
        .set("UserName", this.UserName)
        .set("NewPassword", this.Password)
        .set("ResetToken", this.ResetPwd);
      const headers = new HttpHeaders({
          'Content-Type': 'application/x-www-form-urlencoded'
      });
      this.http.post<boolean>( "api/account/resetpassword", body, { headers } ).subscribe({
          next: async (data) => {
              if (data == true){
                this.errorMsgs = ["Password reset successfully"];
                await this.sleep(3000);
                this.router.navigate(["/account/login"]);
              }else{
                this.errorMsgs = ["An error has ocurred"];
                await this.sleep(3000);
                this.router.navigate(["/account/sendresetpassword"]);
              }
          },
          error: err => {
              console.log("HTTP Error Signing In: ", err);
          }
      });
    }
  }
}