import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AuthService } from '../../Services/auth.service';

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.scss'],
})
export class RegisterComponent {
  form: any = {
    email: null,
    password: null,
    passwordRepeat: null,
    username: null,
  };
  isSuccessful = false;
  isSignUpFailed = false;
  errorMessage = '';

  checkPasswordFailed = false;

  /**
   * @param  {AuthService} privateauthService
   * @param  {Router} privaterouter
   */
  constructor(private authService: AuthService, private router: Router) {}

  /**
   * On submit, send user information to backend
   */
  onSubmit(): void {
    // validate that passwords match
    if (this.form.password === this.form.passwordRepeat) {
      this.checkPasswordFailed = false;
      const { email, username, password } = this.form;
      this.authService.register(email, username, password).subscribe(
        (data) => {
          this.isSuccessful = true;
          this.isSignUpFailed = false;
          this.router.navigate(['/login']);
        },
        (err) => {
          this.errorMessage = err.error.message;
          this.isSignUpFailed = true;
        }
      );
    } else {
      this.checkPasswordFailed = true;
    }
  }
}
