import { Component, OnInit } from '@angular/core';
import { AuthService } from '../auth/auth.service';
import { SignupInfo } from '../auth/signup-info';
import { AbstractControl, FormBuilder, FormControl, FormGroup, Validators } from "@angular/forms";
import Validation from "../validation";
import { MatSnackBar } from "@angular/material/snack-bar";
import { Router } from "@angular/router";

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.css']
})

export class RegisterComponent implements OnInit {
  form: FormGroup = new FormGroup({
    email: new FormControl(''),
    password: new FormControl(''),
    confirmPassword: new FormControl(''),
  });
  signupInfo?: SignupInfo;
  isSignedUp = false;
  isSignUpFailed = false;

  constructor(private authService: AuthService,
              private formBuilder: FormBuilder,
              private _snackBar: MatSnackBar,
              private router: Router) {
  }

  ngOnInit(): void {
    this.form = this.formBuilder.group({
      email: ['', [Validators.required, Validators.email]],
      password: ['', [Validators.required, Validators.minLength(8), Validators.maxLength(40)]],
      confirmPassword: ['', Validators.required]
    }, {
      validators: [Validation.match('password', 'confirmPassword')]
    })
  }

  get f(): { [key: string]: AbstractControl } {
    return this.form.controls;
  }

  onSubmit() {
    if (this.form.invalid) {
      return;
    }

    this.signupInfo = new SignupInfo(this.form.value.email, this.form.value.password);

    this.authService.signUp(this.signupInfo).subscribe(
      data => {
        this.isSignedUp = true;
        this.isSignUpFailed = false;
        this.router.navigate(['/auth/login']);
      },
      error => {
        this._snackBar.open(error.error?.message || 'Oops! Error occurred', 'Dismiss');
        this.isSignUpFailed = true;
      }
    );
  }
}
