import { Component, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';
import { takeUntil } from 'rxjs/operators';
import { UtilsService } from '../../../oneit/services/utils.service';
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 toasterService: ToasterService,
        private authService: AuthService,
        private utilsService: UtilsService,
        private helperService: HelperService
    ) {
        super();
    }

    forgot(): void {
        if (this.form.invalid) {
            return this.helperService.validateAllFormFields(this.form);
        }
        this.isLoading = true;
        this.authService.forgot(this.forgotForm)
            .pipe(takeUntil(this.componentInView))
            .subscribe(response => {
                this.isLoading = false;
                if (response.emailSent) {
                    this.emailSent = true;
                    this.toasterService.success('Please check your email for instructions.');
                }
            }, err => {
                this.isLoading = false;
                this.utilsService.handleError(err);
            });
    }

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

}
