import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { CommonFunctionService } from 'src/app/core/common/common-function.service';
import { securityFunctions } from 'src/app/core/common/security';
import { ValidationService } from 'src/app/core/common/validation.service';
import { API } from 'src/app/core/services/api.service';

@Component({
  selector: 'app-forget-password',
  templateUrl: './forget-password.component.html',
})
export class ForgetPasswordComponent implements OnInit {


  constructor(
    private router: Router,
    public fb: FormBuilder,
    public validationService: ValidationService,
    public ApiServ: API,
    private route: ActivatedRoute,
    public commonService: CommonFunctionService

  ) { }
  showPass = false;
  confirmPass = false;
  ResetPswdForm: FormGroup;

  ngOnInit(): void {
    this.ResetPswdForm = this.fb.group({
      Password: this.validationService.passwordV2,
      confirm_password: this.validationService.required,
      EncryptedData: [''],
    });
    this.route.queryParams.subscribe((key_obj) => {
      if (key_obj) {
        this.ResetPswdForm.get('EncryptedData').setValue(key_obj['key']);
        this.checkResetPassAllow(key_obj['key'])
      }
    });
  }
  ResetPassword() {
    if (this.ResetPswdForm.status == 'INVALID') {
      this.validationService.showValidationsMsg(this.ResetPswdForm);
      return;
    }
    let reset_pswd_obj_val = this.ResetPswdForm.getRawValue();
    if (reset_pswd_obj_val.Password != reset_pswd_obj_val.confirm_password) {
      this.commonService.showMessage(false, 'Your password does not match with confirm password')
      return;
    }
    let data = {
      Password: reset_pswd_obj_val.Password,
      EncryptedData: reset_pswd_obj_val.EncryptedData,
    };
    let Object = {
      key: securityFunctions.encryptRSA(securityFunctions.rsa_public_key, JSON.stringify(data)),
    };
    this.ApiServ.AdminGoPost('/ExtranetUserMaster/UpdatePassword', Object).subscribe(res => {
      if (res.resp) {
        this.commonService.showMessage(true, 'Your password has been changed successfully.')
      }
      else {
        this.commonService.showMessage(res['Resp'], res['Message'])
      }
      setTimeout(() => {
        res.Resp ? this.router.navigate(['/Auth/Login']) : '';
      }, 500);
    })
  }
  btnClick() {
    this.router.navigateByUrl("Auth/Login");
  };

  showMsgValid;
  checkResetPassAllow(dataObj) {
    this.ApiServ.AdminGOGet("/ExtranetUserMaster/IsLinkValid/" + dataObj + '/true').subscribe(res => {
      if (res) {
        this.showMsgValid = res
      }
    })
  }
  onKeyUp(event: KeyboardEvent) {
    if (event.keyCode === 13) { // If Enter key is pressed
      this.ResetPassword();
    }
  }
}
