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

@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.isLoading = false;
                this.hs.oneItHttpResponse(response);
                if (response.emailSent) {
                    this.emailSent = true;
                    this.ts.success('Please check your email for instructions.');
                }
            }, err => {
                this.isLoading = false;
                this.hs.handleHttpError(err);
            });
    }

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

}
