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

import {AuthenticationService} from '@app/_services';

@Component({
  selector: 'auth-forget',
  templateUrl: 'forget.component.html',
  styleUrls: ['forget.component.scss', '../login/login.component.scss']
})
export class ForgetComponent implements OnInit {
  form: FormGroup;
  loading = false;
  success = false;
  error = '';

  constructor(private formBuilder: FormBuilder, private route: ActivatedRoute, private router: Router, private authenticationService: AuthenticationService) {
    //if (this.authenticationService.oauthTokenValue) this.router.navigate(['']).then();
  }

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

  get f() {
    return this.form.controls;
  }
  get email() {
    return this.f?.email?.value;
  }

  onSubmit() {
    if (this.form.invalid) return;
    this.loading = true;
    this.authenticationService.forget(this.email).subscribe(res => {
      this.success = true;
      this.loading = false;
    }, error => {
      this.setError(error.message);
      this.loading = false;
    });
  }

  setError(error: string) {
    let trans = {'The given data was invalid.': 'Указанный адрес почты не найден'};
    this.error = trans[error] || error;
  }

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

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