import { Component, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';
import { takeUntil } from 'rxjs/operators';
import { BaseComponent } from '../../base/base.component';
import { AuthService } from '../../services/auth.service';
import { HelperService } from '../../services/helper.service';
import { ToasterService } from '../../services/toaster.service';
import { EXTERNAL_LINKS } from '../../config/constants';

@Component({
  selector: 'app-forgot-password',
  templateUrl: './forgot-password.component.html',
  styleUrls: ['./forgot-password.component.scss']
})
export class ForgotPasswordComponent extends BaseComponent {

    year = new Date().getFullYear();
    forgotForm = {
        username: ''
    };
    emailSent = false;

    @ViewChild('form') form: NgForm;

    constructor(
        private hs: HelperService,
        private ts: ToasterService,
        private as: AuthService
    ) {
        super();
    }

    forgot(): void {
        if (this.form.invalid) {
            return this.hs.validateAllFormFields(this.form);
        }
        this.isLoading = true;
        this.as.forgot(this.forgotForm)
            .pipe(takeUntil(this.componentInView))
            .subscribe(response => {
                this.hs.oneItHttpResponse(response);
                if (response.emailSent) {
                    this.emailSent = true;
                    this.ts.success('Please check your email for instructions.');
                }
                this.isLoading = false;
            }, err => {
                this.hs.handleHttpError(err);
                this.isLoading = false;
            });
    }

    openPrivacyPolicy(): void {
        window.open(EXTERNAL_LINKS.PRIVACY_POLICY, '_blank');
    }

}
