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-verifyemail',
  templateUrl: './verifyemail.component.html',
  imports: [ FormsModule, CommonModule ]
})
export class VerifyEmailComponent {
  
  UserName: string = "";
  Guid: string = "";
  Result: string = "";
  
  constructor( private http: HttpClient, private router: Router, private route: ActivatedRoute, private title: Title ) {
    this.title.setTitle("Verify Email | Mistox");
    this.route.queryParams.subscribe(params => {
      this.UserName = params['UserName'] || '';
      this.Guid = params['Guid'] || '';
    });
  }

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

  async onSubmit() {
    // Send to server and wait for response
    const body = new HttpParams()
      .set("UserName", this.UserName)
      .set("EmailToken", this.Guid);
    const headers = new HttpHeaders({
        'Content-Type': 'application/x-www-form-urlencoded'
    });
    this.http.post<boolean>( "api/account/verifyemail", body, { headers } ).subscribe({
        next: async (data) => {
            if (data == true){
              this.Result = "Verified Email Successfully";
            }else{
              this.Result = "Email was not able to be verified please resend email";
            }
            await this.sleep(3000);
            this.router.navigate(["/"]);
        },
        error: err => {
            console.log("HTTP Error Signing In: ", err);
        }
    });
  }
}