import { Component, OnInit } from '@angular/core';
import { UntypedFormBuilder, UntypedFormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { AuthenticationDto } from 'src/app/_dto/authentication.dto';
import { AuthService } from 'src/app/_providers/_services/auth.service';
import { ErrorTranslateService } from 'src/app/_providers/_services/error-translate.service';
import { UiService } from 'src/app/_providers/_services/ui.service';

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

  img: string;

  loginForm: UntypedFormGroup;

  user: AuthenticationDto = new AuthenticationDto();

  forgotCard:boolean = false

  config = {
    allowNumbersOnly: true,
    length: 6,
    inputStyles: {
      width: "25px",
      height: "25px",
    },
  }
  otpValue: any;

  isVisibleOtp: boolean = false;

  loading: boolean = false;

  timeOut: boolean = false;

  timeLeft: number;

  time: any;

  isNewPasswordScreen: boolean = false;

  institute: any;

  constructor(
    private _activeRouter: ActivatedRoute,
    private formBuilder: UntypedFormBuilder,
    private _ui: UiService,
    private errorTranslateService: ErrorTranslateService,
    private service: AuthService,
    private router: Router
  ) { }

  async ngOnInit() {

    this.loginForm = this.formBuilder.group({
      username: [''],
      password: [''],
      confpassword: [''],
    });

    await this._activeRouter.queryParams
      .subscribe(
        async (params) => {
          let school = params.school;
          this.institute = params.school;
          this.img = "../../../../assets/accurate/images/" + school + ".png"
        });
  }

  async sendOTP() {
    this.timeOut = true;
    if (!this.user.username || this.user.username.trim() == "") {
      this._ui.toastMessage(this.errorTranslateService.translate("userNameCantbeBlank"));
      this.loading = false;
      this.timeOut = false;
      return;
    }
    if (!this._ui.emailValidation(this.user.username)) {
      this._ui.toastMessage(this.errorTranslateService.translate("enterAValidEmailID"));
      return;
    }

    await this.service.sendOtp({ email: this.user.username }, 'F').then(res => {
      this.loading = false;
      this.isVisibleOtp = true;
      this._ui.toastMessage(this.errorTranslateService.translate("otpSendSuccess"));
    }, (err) => {
      this.timeOut = false;
      console.log("-------err-----", err);
      this._ui.toastMessage(err.message ? err.error.message : this.errorTranslateService.translate('errInSave'), 3000);
    });
    this.setTimer()
  }

  setTimer() {
  //  console.log("here");
    this.timeLeft = 300;
    this.time = setInterval(() => {
      if (this.timeLeft > 0) {
        this.timeLeft--;
      } else {
        this.timeOut = false;
        clearInterval(this.time);
      }
    }, 1000)

  }

  async onVerifyOtp() {
    if (!this.otpValue || this.otpValue.length != 6) {
      this._ui.toastMessage(this.errorTranslateService.translate("enterValidOtp"));
      return
    }
    if (this.otpValue && this.user.username) {
      let body: { otp: string, email: string } = { otp: '', email: '' };
      body.otp = this.otpValue;
      body.email = this.user.username;
      await this.service.verifyOtp(body, 'F').then(res => {
        // this.visibleOtp = false;
        // this.showNewPassword = true;
        this._ui.toastMessage(this.errorTranslateService.translate("otpVerifiedSuccess"));

        this.isNewPasswordScreen = true;
      }, (err) => {
        console.log("-------err-----", err);
        this._ui.toastMessage(err.message ? err.error.message : this.errorTranslateService.translate('errInSave'), 3000);
      })
    }
  }

  async resendOTP() {
    this.timeOut = true;
    this.otpValue = null;
    this.setTimer();
    setTimeout(() => {
    }, 0);
    if (this.user.username && !(this.user.username.trim() == "")) {
      await this.service.sendOtp({ email: this.user.username }, 'FR').then(async res => {
        this._ui.toastMessage(this.errorTranslateService.translate("otpSendSuccess"));
      }, (err) => {
        this._ui.toastMessage(err.message ? err.error.message : this.errorTranslateService.translate('errInSave'), 3000);
      })
    }
    else
      this._ui.toastMessage(this.errorTranslateService.translate("userNameCantbeBlank"));
  }

  onOtpChange(otp) {
    this.otpValue = otp;
   // console.log("==otp==", this.otpValue.length);
  }

  goToLogin() {
    this.router.navigate(["auth/login"]);
  }

  async passwordPreSave(): Promise<boolean> {
    if (!this.user.password || this.user.password == "" || this.user.password.trim() == "") {
      this._ui.toastMessage(this.errorTranslateService.translate("passwordCantbeBlank"));
      return false;
    }
    if (this.user.password.length < 6) {
      this._ui.toastMessage(this.errorTranslateService.translate("minimumPasswordLenght"));
      return false;
    }
    if (!this.user.confpassword || this.user.confpassword == "" || this.user.confpassword.trim() == "") {
      this._ui.toastMessage(this.errorTranslateService.translate("confirmPasswordCantbeBlank"));
      return false;
    }
    if (this.user.password != this.user.confpassword) {
      this._ui.toastMessage(this.errorTranslateService.translate("passwordMismatch"));
      return false;
    }
    return true;
  }

  async onSubmit() {
    if (!(await this.passwordPreSave())) {
      return;
    }

    this.service.forgotPassword({ pass: this.user.password, email: this.user.username, otp: this.otpValue }).then(async (res) => {
      this._ui.toastMessage(this.errorTranslateService.translate("passwordChangeSuccess"));
      await this.router.navigate(["auth/login"]);

    }, (err) => {
      console.log("--", err);
      this._ui.toastMessage(err.message ? err.error.message : this.errorTranslateService.translate('errInSave'), 3000);

    })
  }

}
