import {Component, OnInit} from '@angular/core';
import {Router, ActivatedRoute} from '@angular/router';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';

import {AuthenticationService} from '@app/_services';
import {Subscription} from "rxjs";

@Component({
  selector: 'auth-signup',
  templateUrl: 'signup.component.html',
  styleUrls: ['signup.component.scss', '../login/login.component.scss']
})
export class SignupComponent implements OnInit {
  form: FormGroup;
  loading = false;
  error = '';
  asyncErrors: any = {};
  subscription: Subscription;

  constructor(private formBuilder: FormBuilder, private router: Router, private route: ActivatedRoute, private authenticationService: AuthenticationService) {
    //this.subscription = this.authenticationService.user.subscribe(user => {
    //  if (user) this.router.navigate([this.route.snapshot.queryParamMap.get('returnUrl')?.split('(')[0] || 'applications']).then();
    //});
  }

  ngOnInit() {
    this.form = this.formBuilder.group({
      email: ['', [Validators.required, Validators.email]],
      name: ['', Validators.required],
      phone: [''],
      password: ['', Validators.required],
      passwordConfirmation: ['', Validators.required]
    });
  }

  ngOnDestroy() {
    this.subscription?.unsubscribe();
  }

  get f() {
    return this.form.controls;
  }
  get email() {
    return this.f.email;
  }
  get name() {
    return this.f.name;
  }
  get password() {
    return this.f.password;
  }
  get confirmation() {
    return this.f.passwordConfirmation;
  }

  onSubmit() {
    this.form.markAllAsTouched();
    if (this.form.invalid) return;
    this.loading = true;
    this.authenticationService.signup(this.form.value).subscribe(res => {
      this.authenticationService.getToken(this.email.value, this.password.value).subscribe(res => {
        this.authenticationService.saveToken(res);
        this.close();
      });
    }, error => {
      this.setError(error);
      this.loading = false;
    });
  }

  setError(error: any) {
    this.asyncErrors = error.errors;
    for (let prop in error.errors) {
      if (error.errors.hasOwnProperty(prop)) this.f[prop].setErrors({custom: true});
    }
    let trans = {'The given data was invalid.': 'Проверьте правильность заполнения формы'};
    this.error = trans[error.message] || error.message;
  }

  close() {
    this.authenticationService.popup(null);
  }

  login() {
    this.authenticationService.popup('login');
  }
}
