import { Component, OnInit } from '@angular/core';
import { AuthService } from '../services/auth.service';
import { ToastService } from '../services/toast.service';
import { Router } from '@angular/router';
import { LoadingController } from '@ionic/angular';

@Component({
    selector: 'app-forgot-password',
    templateUrl: './forgot-password.page.html',
    styleUrls: ['./forgot-password.page.scss'],
})
export class ForgotPasswordPage implements OnInit {
    email: string = '';
    otp: string | number = '';
    newPassword: string = '';

    loader: any;

    stepType: 'EMAIL' | 'OTP' | 'RESET' = 'EMAIL';

    constructor(
        private authService: AuthService,
        private toastService: ToastService,
        private router: Router,
        public loadingController: LoadingController
    ) { }

    ngOnInit() {
    }

    async presentLoading() {
        this.loader = await this.loadingController.create({
          message: 'Please wait...',
          spinner: 'dots',
          mode: 'ios'
        });
        await this.loader.present();
    }

    ionViewDidEnter() {
        document.querySelector('.menu-icon-holder').classList.add('hide');
    }

    getOtp() {
        this.presentLoading();
        
        this.authService.forgotPassword(this.email).then(() => {
            this.loader.dismiss();
            this.toastService.presentToast("OTP Sent to your Email ID", "success");
            this.stepType = 'OTP';
        }, () => {
            this.loader.dismiss();
            this.toastService.presentToast("Failed to send OTP, Please check your credentials", "danger");
        });
    }

    verifyOtp() {
        this.presentLoading();
        
        this.authService.validateOtpForForgotPassword({ email: this.email, otp: this.otp }).then(() => {
            this.toastService.presentToast("Verified", "success");
            this.stepType = 'RESET';
            this.loader.dismiss();
        }, () => {
            this.loader.dismiss();
            this.toastService.presentToast("Verification failed, please try again", "danger");
        });
    }

    resetPassword() {
        let credentials = {
            email: this.email,
            login_type: "USER",
            password: this.newPassword,
            reEnteredPassword: this.newPassword
        };

        this.presentLoading();

        this.authService.resetPasswordForEmail(credentials).then(() => {
            this.loader.dismiss();
            this.toastService.presentToast("Password Reset Complete", "success");
            this.router.navigate(['/login']);
            this.stepType = 'EMAIL';
        }, () => {
            this.loader.dismiss();
            this.toastService.presentToast("Please check your password", "danger");
        });
    }

}
