import { Component, OnInit } from '@angular/core';
import { ConfirmedValidator } from '../../validation';
import {
  FormBuilder,
  FormGroup,
  Validators,
} from '@angular/forms';
import { AuthserviceService } from '../../authservice.service';
import { ServicesService } from '../../services.service';
import { NgxSpinnerService } from 'ngx-spinner';
import { Router } from '@angular/router';
import { ActivatedRoute } from '@angular/router';
import { LoginflowService } from '../../data/loginflow.service';
@Component({
  selector: 'app-changepassword',
  templateUrl: './changepassword.component.html',
  styleUrls: ['./changepassword.component.scss'],
})
export class ChangepasswordComponent implements OnInit {
  public LoginForm: FormGroup;
  password: any;
  Confirmpass: any;
  PassLength: boolean = false;
  strangth = 0;
  IsSmall: boolean = false;
  IsUpper: boolean = false;
  Number: boolean = false;
  IsSpecial: boolean = false;
  PassWidth = 0;
  PassMsg = 'Poor';
  oldpassword: any;
  data: any;
  changepasstype = 'password';
  submitted = false;
  CongratulationsModal: boolean = false;
  code: any;
  dataqr: any;
  checkTrue = false;
  elementType: 'url';
  value: any = '';
  newdata: any;
  email: any;
  realpassword: any;
  Old2FAValue: boolean = false;
  check2FAReset: boolean = false;
  devicecode: any;
  authyPasswordEnbled: boolean = false;
  constructor(
    public ActiveRoute: ActivatedRoute,
    public fb: FormBuilder,
    public auth: AuthserviceService,
    public service: ServicesService,
    public spinner: NgxSpinnerService,
    public router: Router,
    public LoginflowService: LoginflowService
  ) {
    var setlogin = this.auth.isLoggedIn();
    if (!setlogin) {
      this.router.navigate(['/login']);
    }
  }
  async ngOnInit() {
    this.LoginForm = this.fb.group(
      {
        password: [
          '',
          [
            Validators.required,
            Validators.pattern(
              '(?=.*[A-Za-z])(?=.*[0-9])(?=.*[$@$!#^~%*?&,.<>"\'\\;:{\\}\\[\\]\\|\\+\\-\\=\\_\\)\\(\\)\\`\\/\\\\\\]])[A-Za-z0-9d$@].{7,}'
            ),
          ],
        ],
        Confirmpass: ['', Validators.required],
      },
      {
        validator: ConfirmedValidator('password', 'Confirmpass'),
      }
    );
    // await this.getTwoFactTab();
    var password = window.localStorage.getItem('domaindata');
    var set = atob(password);
    this.oldpassword = JSON.parse(<string>set);
    if (!this.oldpassword) {
      this.spinner.hide();
      this.router.navigate(['/login']);
    }
    try {
      // this.spinner.show();
      var data = window.localStorage.getItem('userdetails');
      if (data) {
        var jsonData = JSON.parse(<string>data);
        var password = window.localStorage.getItem('domaindata');
        var set = atob(password)
        var passwordset = JSON.parse(<string>set);
        if (jsonData.email && passwordset) {
          this.email = jsonData.email;
          this.realpassword = passwordset
          await this.auth.Getqrcode(jsonData.email, passwordset).then(dataset => {
            if (dataset && dataset[0].StatusCode == 1) {
              this.newdata = dataset;
              this.value = dataset[0].code;
              this.dataqr = dataset[0].secretCode;
              this.devicecode = dataset[0].devicecode;
              this.spinner.hide();
            }
            else {
              this.spinner.hide();
              this.authyPasswordEnbled = true;
            }
          })
        }
        else {
          this.spinner.hide();
          this.router.navigate(['/login']);
        }
      }
      else {
        this.spinner.hide();
        this.router.navigate(['/login']);
      }
    } catch {
      this.spinner.hide();
    }
  }
  async getQRCode() {
    var password = window.localStorage.getItem('domaindata');
    var set = atob(password);
    this.oldpassword = JSON.parse(<string>set);
    if (!this.oldpassword) {
      this.spinner.hide();
      this.router.navigate(['/login']);
    }
    try {
      this.spinner.show();
      var data = window.localStorage.getItem('userdetails');
      if (data) {
        var jsonData = JSON.parse(<string>data);
        var password = window.localStorage.getItem('domaindata');
        var set = atob(password)
        var passwordset = JSON.parse(<string>set);
        if (jsonData.email && passwordset) {
          this.email = jsonData.email;
          this.realpassword = passwordset
          await this.auth.Getqrcode(jsonData.email, passwordset).then(dataset => {
            if (dataset && dataset[0].StatusCode == 1) {
              this.newdata = dataset;
              this.value = dataset[0].code;
              this.dataqr = dataset[0].secretCode;
              this.devicecode = dataset[0].devicecode;
              this.spinner.hide();
            }
            else {
              if (dataset[0].message == "callback.totpRequired is not a function") {
                this.authyPasswordEnbled = true;
                this.spinner.hide();
              }
              else {
                this.authyPasswordEnbled = true;
                this.spinner.hide();
              }
            }
          })
        }
        else {
          this.spinner.hide();
          this.router.navigate(['/login']);
        }

      }
      else {
        this.spinner.hide();
        this.router.navigate(['/login']);
      }
    } catch {
      this.spinner.hide();
    }
  }
  async GeneratedQR() {
    try {
      var data = window.localStorage.getItem('userdetails');
      var jsonData = JSON.parse(<string>data);
      var password = window.localStorage.getItem('domaindata');
      var set = atob(password)
      var passwordset = JSON.parse(<string>set);
      await this.spinner.show();
      if (passwordset && jsonData.email) {
        await this.auth.ResetMFASetup(jsonData.email, passwordset).then(async dataset => {
          await this.getQRCode();
          this.authyPasswordEnbled = false;
        })
        this.spinner.hide();
      }
      else {
        this.router.navigate(['/login']);
        this.spinner.hide();
      }
    }
    catch {
      this.router.navigate(['/login']);
      this.spinner.hide();
    }
  }
  get f() {
    return this.LoginForm.controls;
  }
  async getTwoFactTab() {
    let data = JSON.parse(localStorage.getItem('userdetails'));

    await this.LoginflowService.versions_getUserByEmail(data.email).then((data) => {
      if (data[0].status == 200) {
        var list = JSON.parse(<string>data[0].json);
        if (list.data[0].two_fact_tab == 1) {
          this.checkTrue = true;
        } else {
          this.checkTrue = false;
        }
        this.check2FAReset = this.checkTrue;
      }
    });
  }
  PasswordCheck() {
    if (this.password) {
      if (this.password.length > 0) {
        this.PassWidth = 0;
        this.IsSmall = false;
        this.IsUpper = false;
        this.Number = false;
        this.IsSpecial = false;
        this.PassLength = false;
        this.PassMsg = 'Poor';
        var cnt = 0;
        if (/[a-z]/.test(this.password)) {
          this.IsSmall = true;
        }
        if (this.password.length >= 8) {
          this.PassLength = true;
        }

        if (/[A-Z]/.test(this.password)) {
          this.IsUpper = true;
        }

        if (/[0-9]/.test(this.password)) {
          this.Number = true;
        }
        if (/[!@#$%^&*()_+]/.test(this.password)) {
          this.IsSpecial = true;
        }

        if (this.PassLength) {
          this.PassWidth += 20;
        }
        if (this.IsSmall) {
          this.PassWidth += 20;
        }
        if (this.IsUpper) {
          this.PassWidth += 20;
        }
        if (this.Number) {
          this.PassWidth += 20;
        }
        if (this.IsSpecial) {
          this.PassWidth += 20;
        }

        if (this.PassWidth == 20 || this.PassWidth == 40) {
          this.PassMsg = 'Poor';
        }
        if (this.PassWidth == 60 || this.PassWidth == 80) {
          this.PassMsg = 'Good';
        }
        if (this.PassWidth == 100) {
          this.PassMsg = 'Strong';
        }
      } else {
        this.PassWidth = 0;
        this.IsSmall = false;
        this.IsUpper = false;
        this.Number = false;
        this.IsSpecial = false;
        this.PassLength = false;
        this.PassMsg = 'Poor';
      }
    } else {
      this.PassWidth = 0;
      this.IsSmall = false;
      this.IsUpper = false;
      this.Number = false;
      this.IsSpecial = false;
      this.PassLength = false;
      this.PassMsg = 'Poor';
    }
  }
  async update() {
    try {
      this.submitted = true;
      if (this.checkTrue == false) {
        await this.verify();
      } else {
        if (this.LoginForm.valid) {
          var Email;
          var datas = localStorage.getItem('userdetails');
          if (datas != undefined || datas != null || datas != '') {
            var data = JSON.parse(<string>datas);
            Email = data.email;
          }
          this.spinner.show();
          await this.auth
            .ResetPassword(Email, this.oldpassword, this.password)
            .then(async (resetdata) => {
              if (resetdata[0].StatusCode == 1) {
                var passwordsession = btoa(JSON.stringify(this.password));
                window.localStorage.setItem('domaindata', passwordsession);
                var cohort_id = localStorage.getItem('cohort_id');
                var user_id = localStorage.getItem('CisspUserId');

                await this.addActivityTracker(user_id, this.email, cohort_id, "Change Password", "Change Password - Password change successfully");
                await this.LoginflowService.UpdateUseremail(
                  Email,
                  '0',
                  this.password
                ).then((changepas) => {
                  if (changepas[0].StatusCode == 1) {
                    this.reset();
                    this.spinner.hide();
                    this.service.ShowSuccess(resetdata[0].message);
                  } else {
                    this.spinner.hide();
                    this.service.ShowError(changepas[0].message);
                  }
                });
              } else {
                if (resetdata[0].message == 'Incorrect username or password.') {
                  var cohort_id = localStorage.getItem('cohort_id');
                  var user_id = localStorage.getItem('CisspUserId');
                  await this.addActivityTracker(user_id, this.email, cohort_id, "Change Password", "Change Password failed - Please enter valid old passsword");
                  this.spinner.hide();
                  this.service.ShowError('Please enter valid old passsword !');
                } else {
                  this.spinner.hide();
                  this.service.ShowError(resetdata[0].message);
                }
              }
            });
        } else {
        }
      }
    } catch {
      this.spinner.hide();
    }
  }
  async reset() {
    this.oldpassword = '';
    this.Confirmpass = '';
    this.password = '';
    this.PassWidth = 0;
    this.IsSmall = false;
    this.IsUpper = false;
    this.Number = false;
    this.IsSpecial = false;
    this.PassLength = false;
    this.PassMsg = 'Poor';
    this.code = '';
    if (this.Old2FAValue) {
      this.checkTrue = this.check2FAReset;
      let id = localStorage.getItem('CisspUserId');
      let two_fact_tab = this.checkTrue ? "1" : "0";
      await this.LoginflowService.updateTwoFactTab(id, two_fact_tab).then((response) => { });
    }
    this.Old2FAValue = false;
  }
  showpass(item) {
    this.changepasstype = item;
  }
  retuey() {
    window.location.reload();
  }
  async addActivityTracker(user_id, email, cohort_id, type, message) {
    await this.service.addActivityTracker(user_id, email, cohort_id, type, message);
  }
  async checkauth() {
    if (!this.Old2FAValue) {
      this.check2FAReset = this.checkTrue;
      this.Old2FAValue = true;
    }
    this.checkTrue = !this.checkTrue;
    let msg = "MFA - Disabled MFA";
    if (this.checkTrue) {
      msg = "MFA - Enabled MFA"
    }
    var cohort_id = localStorage.getItem('cohort_id');
    var user_id = localStorage.getItem('CisspUserId');
    await this.addActivityTracker(user_id, this.email, cohort_id, "MFA", msg);

    let two_fact_tab = this.checkTrue ? "1" : "0";
    await this.LoginflowService.updateTwoFactTab(user_id, two_fact_tab).then((response) => { });
  }
  async verify() {
    if (this.code == "" || this.code == undefined) {
      this.service.ShowError('Please enter code');
    }
    else if (this.code.trim() && this.code.length == 6) {
      await this.spinner.show()
      await this.auth.verify(this.email, this.realpassword, this.code, this.newdata[0].data).then(async (set) => {
        if (set[0].StatusCode == 1) {
          this.code = "";
          await this.checkauth();
          await this.spinner.hide()
          this.CongratulationsModal = true;
        }
        else {
          await this.spinner.hide()

          this.service.ShowError("You have entered Invalid code. Please try again with valid code.")
        }
      })
    }
    else {
      await this.spinner.hide()
      this.service.ShowError("Please enter the 6-digit one-time password that has been generated by your app")
    }
    await this.spinner.hide()

  }
  thankyou() {
    if (this.code) {
      var data = window.localStorage.getItem('userdetails');
      var jsonData = JSON.parse(<string>data);
      this.LoginflowService.verify(this.code, jsonData.email).then((data) => {
        if (data[0].status == 200) {
          var list = JSON.parse(<string>data[0].json);
          if (list.data.success == 'true') {
            this.service.ShowSuccess('Authentication successfully');
          } else {
            this.service.ShowError('Invalid code');
          }
        }
      });
    } else {
      this.service.ShowError('Please enter code');
    }
  }
}
