import { Component, HostListener, OnInit, ViewChild } from '@angular/core';
import { LogoLinkOptions } from '../../ui/logo/logo.component';
import { UntypedFormBuilder, Validators } from '@angular/forms';
import { AuthService } from '../auth.service';
import { ConfigService } from '../../config/config.service';
import { FormErrorsComponent } from '../../error-handling/form-errors/form-errors.component';
import { of } from 'rxjs';
import { ThemingService } from '@shared/ui/theming/theming.service';

@Component({
  selector: 'app-forgot-password',
  templateUrl: './forgot-password.component.html',
  styleUrls: ['./forgot-password.component.scss']
})
export class ForgotPasswordComponent implements OnInit {
  forgotPassForm = this.formBuilder.group({
    email: ['', Validators.required],
  });
  logoLinkOptions = new LogoLinkOptions(false);
  resetRequested = false;
  cardTopMargin: string;
  loading: boolean;

  @ViewChild('formErrors') formErrors: FormErrorsComponent;

  constructor(
    private formBuilder: UntypedFormBuilder, public auth: AuthService, public config: ConfigService,
    private themingService: ThemingService,
  ) {
  }

  ngOnInit() {
    this.setCardTopMargin(window.innerHeight);
  }

  @HostListener('window:resize', ['$event'])
  onResize(event) {
    this.setCardTopMargin(window.innerHeight);
  }

  private setCardTopMargin(innerHeight) {
    this.cardTopMargin = this.themingService.setOrphanCardMarginTop(innerHeight, 360);
  }

  submit() {
    if (this.forgotPassForm.invalid) {
      return of(null);
    }
    const value = this.forgotPassForm.value;
    this.loading = true;
    this.auth.resetPassword(
      value.email
    ).subscribe(response => {
      this.resetRequested = true;
    }, error => {
      this.formErrors.setBackendErrors(error.error);
    }).add(() => {
      this.loading = false;
    });
  }
}
