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 { Account } from '../../../models/Account';
import { Title } from '@angular/platform-browser';
import { CommonModule } from '@angular/common';

@Component({
  selector: 'account-register',
  templateUrl: './register.component.html',
  imports: [ FormsModule, CommonModule ]
})
export class RegisterComponent {
  userName: string = ""
  email: string = "";
  passwordHash: string = "";
  passwordHash2: string = "";
  error: string = "";

  errorMsgs: string[] = [];
  returnURL: string = '/';

  constructor( private http: HttpClient, private router: Router, private route: ActivatedRoute, private title: Title ) {
    this.title.setTitle("Register | 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 = [];

    // Validate data
    const regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
    if (!regex.test(this.email)){
      this.errorMsgs.push("A valid email is required");
    }
    if (!this.userName) {
      this.errorMsgs.push("The 'username' field is required");
    }
    if (!this.passwordHash) {
      this.errorMsgs.push("The 'password' field is required");
    }
    if (this.passwordHash.length < 6) {
      this.errorMsgs.push("Password must be at least 6 Characters long");
    }
    if (this.passwordHash !== this.passwordHash2){
        this.errorMsgs.push("Passwords don't match");
    }
    if (this.errorMsgs.length > 0) {
      return;
    }

    // Send to server and wait for response
    this.errorMsgs.push("Waiting for response from server");
    const body = new HttpParams()
      .set("Email", this.email)
      .set("UserName", this.userName)
      .set("PasswordHash", this.passwordHash);
    const headers = new HttpHeaders({
      'Content-Type': 'application/x-www-form-urlencoded'
    });
    this.http.post<Account>( "api/account/register", body, { headers } ).subscribe({
      next: async (data) => {
        this.errorMsgs = ["Account Created"];
        await this.sleep(3000);
        this.router.navigate([this.returnURL]);
      },
      error: err => {
        this.errorMsgs = [ err.error ]
      }
    });
  }
}