import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AuthService } from './../../services/auth.service';
import { NotifierService } from "angular-notifier";
import { AbstractControl, FormBuilder, FormGroup, Validators, ValidatorFn } from '@angular/forms';

@Component({
  selector: 'app-signup',
  templateUrl: './singup.component.html',
  styleUrls: ['./singup.component.scss']
})
export class SignupComponent implements OnInit { 
  private readonly notifier: NotifierService;
  constructor(
    private authService: AuthService,
    private router: Router,
    notifierService: NotifierService,
    private formBuilder: FormBuilder) {this.notifier = notifierService;}
  form = new FormGroup({});
  submitted = false;
  sended = false;
    ngOnInit(): void {
      this.form = this.formBuilder.group(
        {
          fullname: ['', Validators.required],
          username: [
            '',
            [
              Validators.required,
              Validators.minLength(6),
              Validators.maxLength(20)
            ]
          ],
          email: ['', [Validators.required, Validators.email]],
          password: [
            '',
            [
              Validators.required,
              Validators.minLength(8),
              Validators.maxLength(40)
            ]
          ],
          confirmPassword: ['', Validators.required],
          acceptTerms: [false, Validators.requiredTrue]
        },
        {
          validators: [this.match('password', 'confirmPassword')]
        }
      );
    }

    match(controlName: string, checkControlName: string): ValidatorFn {
      return (controls: AbstractControl) => {
        const control = controls.get(controlName);
        const checkControl = controls.get(checkControlName);
        if (checkControl?.errors && !checkControl.errors.matching) {
          return null;
        }
        if (control?.value !== checkControl?.value) {
          controls.get(checkControlName)?.setErrors({ matching: true });
          return { matching: true };
        } else {
          return null;
        }
      };
    }

  get f(): { [key: string]: AbstractControl } {
    return this.form.controls;
  }
  onSubmit(): void {
    this.submitted = true
    if (this.form.invalid) {
      //this.notifier.notify("warning",(JSON.stringify("Invalid form")));
      return;
    }
    this.onSign();
    //console.log(JSON.stringify(this.form.value, null, 2));
  }
  onReset(): void {
    
    this.submitted = false;
    this.sended = false;
    this.form.reset();
  }

  onSign (){
    this.authService.signup(this.form.value.fullname, this.form.value.username, this.form.value.email, this.form.value.password, this.form.value.confirmPassword).subscribe(
      success => {console.log('SUCCESS');},
      error => {console.log(error.statusText);
                if (error.statusText == 'OK') {this.sended = true}
                else{this.notifier.notify("warning",(JSON.stringify("There might be a problem with your registration. Please try again later.")));}   
      }
    );
  }

}
