
import { Component, OnInit } from '@angular/core';
import { ElementRef } from '@angular/core';
import { NavController, Platform } from '@ionic/angular';
import { TranslatorService } from 'src/app/hmg-common/services/translator/translator.service';
import { CommonService } from 'src/app/hmg-common/services/common/common.service';
import { SharedDataService } from 'src/app/hmg-common/services/shared-data-service/shared-data.service';
import { SMSCheckRequest } from 'src/app/hmg-common/services/authentication/models/smscheck.request';
import { LoginModel } from '../models/LoginModel';
import { AuthenticationService } from 'src/app/hmg-common/services/authentication/authentication.service';
import { SMSCheckResponse } from 'src/app/hmg-common/services/authentication/models/smscheck.response';
import { Password } from '../models/password';
import { GetLoginInfoRequest } from 'src/app/hmg-common/services/authentication/models/get-login-info.request';
import * as moment from 'moment';

@Component({
  selector: 'app-sms-page',
  templateUrl: './sms-page.page.html',
  styleUrls: ['./sms-page.page.scss']
})

export class SmsPageComponent implements OnInit {
  public static LOGIN_DATA = 'LOGIN_DATA';
  Channel = 0;
  activationCode: string;
  P_SESSION_ID: number;
  P_USER_NAME: string;
  timeInSeconds: any;
  time: any;
  runTimer: any;
  hasStarted: any;
  hasFinished: any;
  remainingTime: any;
  displayTime: any;
  loginTokenID: string;
  public isForgetPwd = false;
  public isExpiredPwd = false;
  public count = 0;
  private loginData = new LoginModel();
  public deviceToken: any;
  public loginTypeData: any;
  public logo = 'assets/icon/login/password.png';
  // tslint:disable-next-line: variable-name
  public smc_code: any = [];
  code: any;
  // tslint:disable-next-line: variable-name
  user_name: string;
  public isPostNoLoad = true;
  loginType: any;
  activeType: any;


  constructor(
    public navCtrl: NavController,
    public translate: TranslatorService,
    public common: CommonService,
    private elementRef: ElementRef,
    public authService: AuthenticationService,
    public sharedData: SharedDataService,
    public platform: Platform,
  ) {}

  ngOnInit() {
    this.activeType=this.common.getActiveTypeLogin();
    console.log("activeType :"+this.activeType);
    this.count = 0;
    this.initTimer();
    this.startTimer();
    this.isForgetPwd = this.sharedData.getSharedData(Password.IS_FORGET_PSW) || false;
    this.isExpiredPwd = this.sharedData.getSharedData(Password.IS_EXPIRED_PSW) || false;
    this.loginData = this.sharedData.getSharedData(AuthenticationService.LOGIN_DATA, false);
    this.deviceToken = this.common.sharedService.getSharedData(AuthenticationService.DEVICE_TOKEN, false);
    // tslint:disable-next-line: triple-equals
    if (this.deviceToken == undefined) {
      this.deviceToken = localStorage.getItem('deviceToken');
    }
    console.log('deviceToken :' + this.deviceToken);
    this.loginTypeData = this.common.sharedService.getSharedData(SMSCheckRequest.SHARED_DATA, false);
    if( this.loginTypeData){
      this.loginType=this.loginTypeData.loginType;

     console.log("loginType :"+this.loginTypeData.loginType);
      }else{
       this.loginType=1;
      }

  }

  initTimer() {
    if (!this.timeInSeconds) {
      this.timeInSeconds = 600;
    }
    this.time = this.timeInSeconds;
    this.runTimer = false;
    this.hasStarted = false;
    this.hasFinished = false;
    this.remainingTime = this.timeInSeconds;
    this.displayTime = this.common.getSecondsAsDigitalClock(this.remainingTime);
  }

  startTimer() {
    this.runTimer = true;
    this.hasStarted = true;
    this.timerTick();
  }

  pauseTimer() {
    this.runTimer = false;
  }

  resumeTimer() {
    this.startTimer();
  }

  timerTick() {
    setTimeout(() => {
      if (!this.runTimer) {
        return;
      }
      this.remainingTime--;
      this.displayTime = this.common.getSecondsAsDigitalClock(this.remainingTime);
      if (this.remainingTime > 0) {
        this.timerTick();
      } else {
        this.hasFinished = true;
        this.pauseTimer();
        this.navCtrl.pop();
      }
    }, 1000);
  }

  ionViewWillLeave() {
    this.pauseTimer();
  }

  checkOTPLength() {
    // tslint:disable-next-line: triple-equals
    if (this.activationCode.length == 4) {
      this.checkVerificationCode();
    }
  }

  checkVerificationCode() {
    this.code = this.smc_code.join('');
    if (this.count < 3) {
      // tslint:disable-next-line: triple-equals
      if (this.code == undefined || this.code == null || this.code == '') {
        //  this.common.showAlert(this.translate.translate('verificationcode.emptyCode'));
      } else {
        this.count = this.count + 1;
        if (this.isForgetPwd || this.isExpiredPwd) {
          this.checkForgetPwdSMS();
        } else {
          this.checkSMS();
        }
      }
    } else {
      const msg: string = this.translate.trPK('general', 'noOfTriesLogin');
      this.common.JustAlertDialog(this.translate.trPK('general', 'ok'), msg);
    }
  }

  public checkSMS() {
      const data = this.sharedData.getSharedData(AuthenticationService.LOGIN_DATA, false);
      const request = new SMSCheckRequest();
      request.LogInTokenID = data.LogInTokenID;
      request.activationCode = this.code; // code;this.activationCode;
      request.P_USER_NAME = data.P_USER_NAME;
      request.MobileNumber = data.MobileNumber;
      this.authService.checkSMS(request, () => {}, this.translate.trPK('general', 'ok')).subscribe((result: SMSCheckResponse) => {
        if (this.common.validResponse(result)) {
          AuthenticationService.servicePrivilage = result.Privilege_List;
          this.authService.setAuthenticatedUser(result).subscribe(() => {
            localStorage.setItem('emp-name', result.MemberInformationList[0].EMPLOYEE_NAME);
            this.user_name = result.MemberInformationList[0].EMPLOYEE_NAME;
            const currDateTime =  moment().format('MMM DD , YYYY HH:mm');
            localStorage.setItem('login-at', currDateTime);
            if (this.platform.is('cordova')) {
              this.insertMobileLogin();
            }
            this.common.openHome();
          });
        }
      });
  }

  public insertMobileLogin() {
        const request = new GetLoginInfoRequest();
        this.authService.setPublicFields(request);
        request.MobileNumber = this.loginData.MobileNumber;
        request.P_USER_NAME = this.loginData.P_USER_NAME;
        request.UserName = this.loginData.P_USER_NAME;
        request.LogInTokenID = this.loginData.LogInTokenID;
        request.CompanyID = 1; // CompanyID
        request.DeviceType = this.common.getDeviceType();
        request.DeviceToken = this.deviceToken; // "5ca8a69cf1804db55264c349edffb99b9d63acd9fa9b6b18956bcb2ad3f2ba36";//this.deviceToken;
        request.LoginType = this.loginTypeData.loginType;
        request.EmployeeName = this.user_name;
        this.authService.insertMobileLoginInfo(request, () => { }, this.translate.trPK('general', 'ok'), this.isPostNoLoad)
        .subscribe((result: any) => {
            console.log('successful insertMobileLogin' );
        });
  }

  public checkForgetPwdSMS() {
    const data = this.sharedData.getSharedData(AuthenticationService.LOGIN_DATA, false);
    const request = new SMSCheckRequest();
    request.LogInTokenID = data.LogInTokenID;
    request.activationCode = this.code; // this.activationCode;
    request.P_USER_NAME = data.P_USER_NAME;
    this.authService.checkForgetSMS(request, () => {}, this.translate.trPK('general', 'ok')).subscribe((result: SMSCheckResponse) => {
        if (this.common.validResponse(result)) {
          if (this.isForgetPwd) {
            this.common.openForgotPassword();
          }
          if (this.isExpiredPwd) {
            this.sharedData.setSharedData(true, Password.IS_EXPIRED_PSW);
            this.common.openChangePassword();
          }
        }
      });
  }

  onChange() {
    // tslint:disable-next-line: only-arrow-functions
    const filtered = this.smc_code.filter(function(el) {
      if (el) {
        return el;
      }
    });
    if (filtered.length === 4) {
      this.checkVerificationCode();
    }
  }

  goToNextInput(e) {
    const key = e.which;
    const t = e.target;
    const sib = t.nextElementSibling;
    const sibPre = t.previousElementSibling;

    if (key !== 9 && (key < 48 || key > 57)) {
      if (key === 8 || key === 46) {
        return true;
      } else {
        e.preventDefault();
        return false;
      }
    }

    if (key === 9) {
      return true;
    }

    if (sib) {
      if (e.target.value === '') {
        sibPre.setFocus();
      } else {
        sib.setFocus();
      }
    }
  }
}
