import { Component, OnInit, Input } from '@angular/core';
import {ButtonSettings} from 'src/app/hmg-common/ui/button/models/button-settingsl';
import {TranslatorService} from 'src/app/hmg-common/services/translator/translator.service';
import { CommonService } from 'src/app/hmg-common/services/common/common.service';
import { LoginRequest } from 'src/app/hmg-common/services/authentication/models/login.request';
import { AuthenticationService } from 'src/app/hmg-common/services/authentication/authentication.service';
import { SharedDataService } from 'src/app/hmg-common/services/shared-data-service/shared-data.service';
import { SendActivationByType } from '../models/sendActivationByType';
import { FingerprintAIO } from '@ionic-native/fingerprint-aio/ngx';
import { GetLoginInfoRequest } from '../../hmg-common/services/authentication/models/get-login-info.request';
import { GetLoginInfoResponse } from '../../hmg-common/services/authentication/models/get-login-info.response';
import { SMSCheckRequest } from 'src/app/hmg-common/services/authentication/models/smscheck.request';
import { SMSCheckResponse } from 'src/app/hmg-common/services/authentication/models/smscheck.response';
import { PushService } from 'src/app/hmg-common/services/push/push.service';
import { Platform } from '@ionic/angular';
import { CheckUserAuthenticationResponse } from 'src/app/hmg-common/services/authentication/models/check-user-auth.response';
import { LoginModel } from '../models/LoginModel';
import * as moment from 'moment';

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

export class ConfirmLoginComponent implements OnInit {
  public logo = 'assets/icon/login/password.png';
  public buttons: any = [];
  isFaceorFinger: any;
  onlySMSBox: any = true;
  public loginData = new LoginModel();
  selectedOption: any;
  lastLogin: any;
  loginTokenID: any;
  deviceToken: any;
  @Input() accessFromOutSide = false;
  @Input() visible = true;
  username: any;
  password: any;
  loginType: any;
  empname: string;
  lastLoginDate: string;
  // tslint:disable-next-line: variable-name
  user_name: string;
  FFloginType: any;
  public isPostNoLoad = true;

  constructor(
    public ts: TranslatorService,
    public cs: CommonService,
    public authService: AuthenticationService,
    public sharedData: SharedDataService,
    private faio: FingerprintAIO,
    public pushService: PushService,
    public platform: Platform,
    ) {
     this.loginData = this.sharedData.getSharedData(AuthenticationService.LOGIN_DATA, false);
     this.deviceToken = this.cs.sharedService.getSharedData(AuthenticationService.DEVICE_TOKEN, false);
     // if device token undefind

     // tslint:disable-next-line: triple-equals
     if (this.deviceToken == undefined) {
      this.deviceToken = localStorage.getItem('deviceToken');
    }
     this.lastLogin = this.cs.sharedService.getSharedData(AuthenticationService.LAST_LOGIN, false);
     this.username = localStorage.getItem('user');
     this.password = localStorage.getItem('password');
     this.empname = localStorage.getItem('emp-name');
  }

  ngOnInit() {
    // **checkIfAvailable FAIO **//
    this.checkIfAvailable();
    // **getSharedData of IMEI_USER_DATA and REGISTER_DATA_FOR_LOGIIN to set defult value **//
    this.username = localStorage.getItem('user');
    this.password = localStorage.getItem('password');
    this.empname = localStorage.getItem('emp-name');
    this.button();
  }



  checkIfAvailable() {
    this.faio.isAvailable().then(
      options => {
        this.isFaceorFinger = options;
        this.button();
      }, () => {
        this.isFaceorFinger = null;
        this.button();
      }
    );
  }

  button() {
    this.buttons = [
      [{
        title: 'login,verify-with-fingerprint',
        url: null,
        icon: 'assets/icon/login/102.png',
        settings: new ButtonSettings(true, true, true, true),
        value: 2,
        disabled: this.isFaceorFinger === 'finger' || this.isFaceorFinger === 'biometric' ? false : true,
        visible: this.onlySMSBox,
        buttonClass: 'buttonClassWhite',
        pClass: 'pClassMyFileIconBlack',
        class: 'nationalIdIcon',
      },
      {
        title: 'login,verify-with-faceid',
        url: null,
        icon: 'assets/icon/login/101.png',
        settings: new ButtonSettings(true, true, true, true),
        value: 3,
        disabled: this.isFaceorFinger === 'face'  ? false : true,
        visible: this.onlySMSBox,
        buttonClass: 'buttonClassWhite',
        pClass: 'pClassMyFileIconBlack',
        class: 'nationalIdIcon',
      },
      {
        title: 'login,verify-with-whatsapp',
        url: null,
        icon: 'assets/icon/login/104.png',
        settings: new ButtonSettings(true, true, true, true),
        value: 4,
        visible: true,
        buttonClass: 'buttonClassWhite',
        pClass: 'pClassMyFileIconBlack',
        class: 'nationalIdIcon',
      },
      {
        title: 'login,verify-with-sms',
        url: null,
        icon: 'assets/icon/login/103.png',
        settings: new ButtonSettings(true, true, true, true),
        value: 1,
        visible: true,
        buttonClass: 'buttonClassWhite',
        pClass: 'pClassMyFileIconBlack',
        class: 'nationalIdIcon'
      }]
    ];
  }

  confirm(el: any) {
    this.selectedOption = this.selectedOption && !this.onlySMSBox ? this.selectedOption : el.value;
    switch (el.value) {
      case 1:

      console.log(el.value);
      localStorage.setItem("login-type",el.value);
       console.log("login-type: "+ localStorage.getItem("login-type"))
       if(this.FFloginType == 3 || this.FFloginType == 2 ){
        this.cs.setActiveTypeLogin(el.value);
       }else{
        this.cs.setActiveTypeLogin(0);

       }
      this.loginWithSMS(el);

        break;
      case 2:
        localStorage.setItem('login-type', el.value);
        this.loginWithFingurePrint(el);
        break;
      case 3:
        localStorage.setItem('login-type', el.value);
        this.faceReconization(el);
        break;
      case 4:

          console.log(el.value);

          localStorage.setItem("login-type",el.value);
           if(this.FFloginType == 3 || this.FFloginType == 2 ){
            this.cs.setActiveTypeLogin(el.value);
           }else{
            this.cs.setActiveTypeLogin(0);

           }
        this.loginWithWhatsapp(el);
        break;
      default:
        break;
    }

    this.cs.sharedService.setSharedData(this.selectedOption, AuthenticationService.LAST_LOGIN);
  }

  loginWithSMS(el) {
    if (!el.disabled) {
        if (this.loginData.LogInTokenID) {
          this.sendActivationCode(1);
        } else {
         // this.checkUserAuthentication(1);
         // this.checkUserAuthentication();**
        }
    }
  }

  loginWithWhatsapp(el) {
    if (!el.disabled) {
        if (this.loginData.LogInTokenID) {
          this.sendActivationCode(2);
        } else {
         // this.checkUserAuthentication(2);
        }
    }
  }



 public sendActivationCode(type: number) {
    const request = new SendActivationByType();
    this.authService.setPublicFields(request);
    request.OTP_SendType = type;
    request.MobileNumber = this.loginData.MobileNumber;

    request.IsMobileFingerPrint =0;

    request.P_USER_NAME=this.loginData.P_USER_NAME;

    request.LogInTokenID =this.loginData.LogInTokenID;

    request.P_LEGISLATION_CODE =this.loginData.P_LEGISLATION_CODE;//"SA";

    // request.VersionID ="2.0";



// request.LanguageID = imeiData && imeiData.PreferredLanguage || request.LanguageID;

    this.authService

      .sendActivationCodeByType(

        request,

        () => { },

        this.ts.trPK("general", "ok")

      )

      .subscribe((result: any) => {
        if (result.isSMSSent) {
          // tslint:disable-next-line: max-line-length
          this.cs.sharedService.setSharedData({MobileNumber: this.loginData.MobileNumber, loginType: this.selectedOption}, SMSCheckRequest.SHARED_DATA);
          this.cs.openSMSPage();
        }
      });
  }


  loginWithFingurePrint(el: any) {
    if (!el.disabled) {
      this.FFloginType = el.value;
      this.startBiometricLoginIfAvailable();
    }
  }

  faceReconization(el: any) {
    if (!el.disabled) {
      this.FFloginType = el.value;
      this.startBiometricLoginIfAvailable();
    }
  }

  private startBiometricLoginIfAvailable() {
    this.faio.isAvailable().then(
      options => {
        this.presentBiometricDialog();
      }, () => {
        alert('not avaliable ');
      }
    );
  }

  private presentBiometricDialog() {
    this.faio.show({
      title: 'Biometric Authetnciation', // (Android Only) | optional | Default: "<APP_NAME> Biometric Sign On"
      subtitle: 'Coolest Plugin ever' , // (Android Only) | optional | Default: null
      description: this.ts.trPK('general', 'auth-please'), // optional | Default: null
      fallbackButtonTitle: this.ts.trPK('general', 'use-pin'), // optional | When disableBackup is false defaults to "Use Pin".
      disableBackup: true,  // optional | default: false
      // clientId: "Fingerprint Authetnciation",
      // clientSecret: "Ate343_9347lajF", // Only necessary for Android
      // disableBackup: true, // Only for Android(optional)
      // localizedFallbackTitle: this.ts.trPK("general", "use-pin"), // Only for iOS
      // localizedReason: this.ts.trPK("general", "auth-please") // Only for iOS
      }).then((result: any) => {
        const request = {
        DeviceType: this.cs.getDeviceType(),
        DeviceToken: this.deviceToken
        };
        // 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;//cs=1 , HMG=2
        this.getMobileInfo(request);
      }).catch((error: any) => {
        console.log(error);
      });
  }

  private getMobileInfo(request: any) {
    this.authService.getLoginInfo(request, () => { }, this.ts.trPK('general', 'ok')).subscribe((result: GetLoginInfoResponse) => {
        if (result.Mohemm_GetMobileLoginInfoList.length > 0) {
          // tslint:disable-next-line: triple-equals
          if ( result.Mohemm_GetMobileLoginInfoList[0].LoginType == 2 || result.Mohemm_GetMobileLoginInfoList[0].LoginType == 3) {
            this.loginTokenID = result.LogInTokenID;
            this.checkSMS();
          } else {
              this.onlySMSBox = false;
              this.button();
          }
        } else {
            this.onlySMSBox = false;
            this.button();
          }
      });

  }

  public checkSMS() {
    const data = this.sharedData.getSharedData(AuthenticationService.LOGIN_DATA, false);
    const request = new SMSCheckRequest();
    request.LogInTokenID = data.LogInTokenID;
    request.activationCode = '';
    request.P_USER_NAME = data.P_USER_NAME;
    request.MobileNumber = data.MobileNumber;
    this.authService.checkSMS(request, () => {}, this.ts.trPK('general', 'ok'))
      .subscribe((result: SMSCheckResponse) => {
        if (this.cs.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.cs.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.cs.getDeviceType();
    request.DeviceToken = this.deviceToken; // "5ca8a69cf1804db55264c349edffb99b9d63acd9fa9b6b18956bcb2ad3f2ba36";//this.deviceToken;
    // request.TokenID=
    request.LoginType = this.selectedOption;
    request.EmployeeName = this.user_name;
    this.authService.insertMobileLoginInfo(request, () => { }, this.ts.trPK('general', 'ok'), this.isPostNoLoad)
      .subscribe((result: any) => {
        console.log('successful insertMobileLoginInfo' );
    });
}

// do silent login
private checkUserAuthentication() {
  this.cs.startLoading();
  const request = new LoginRequest();
  request.P_USER_NAME = this.username;
  request.P_LANGUAGE = 'US'; // this.language;
  request.P_PASSWORD = this.password;
  this.authService
      .login(request, () => {
          console.log('error here');
      }, this.ts.trPK('general', 'ok'))
      .subscribe((result: CheckUserAuthenticationResponse) => {
          console.log('success');
          this.cs.stopLoading();
          if (this.cs.validResponse(result)) {
              this.loginData = new LoginModel();
              this.loginData.LogInTokenID = result.LogInTokenID;
              this.loginData.MobileNumber = result.MemberLoginList.P_MOBILE_NUMBER;
              this.loginData.P_USER_NAME = this.username;
              this.loginData.EmployeeName = this.user_name;
              this.sharedData.setSharedData(this.loginData, AuthenticationService.LOGIN_DATA);
              this.cs.sharedService.setSharedData(this.loginData.P_USER_NAME, LoginRequest.SHARED_DATA);
              this.confirm(this.loginType);
          } else {
              if (result.IsPasswordExpired) {
                 // alert("dont forget to handelpresentPasswordExpiredDialog() ");
                 // this.presentPasswordExpiredDialog(); *****
              }
          }
      });
}

checkAccess(el: any) {
  const data = this.sharedData.getSharedData(AuthenticationService.LOGIN_DATA, false);
  this.loginType = el;
  if (this.accessFromOutSide) {
    this.checkUserAuthentication();
  } else {
      // tslint:disable-next-line: triple-equals
      if (!data == undefined ) {
        this.confirm(this.loginType);
      } else {
        this.checkUserAuthentication();
    }
  }
}

}​
