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-login',
  templateUrl: 'login.component.html',
  styleUrls: ['login.component.scss']
})
export class LoginComponent implements OnInit {
  form: FormGroup;
  loading = false;
  error = '';
  subscription: Subscription;
  public type: string = 'password';

  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] || '']).then();
    //});
  }

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

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

  get f() {
    return this.form.controls;
  }
  get username() {
    return this.f.username.value;
  }
  get password() {
    return this.f.password.value;
  }

  onSubmit() {
    if (this.form.invalid) return;
    this.loading = true;
    this.authenticationService.getToken(this.username, this.password).subscribe(res => {
      this.authenticationService.saveToken(res);
    }, error => {
      this.setError(error.message);
      this.loading = false;
    });
  }

  setError(error: string) {
    let trans = {'The user credentials were incorrect.': 'Имя пользователя или пароль указаны неверно.'};
    this.error = trans[error] || error;
  }

  forget() {
    this.authenticationService.popup(['password','forget']);
  }

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

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