import { Router } from '@angular/router';
import { Component, OnInit, ViewChild } from '@angular/core';
import { WrenchService } from 'src/app/services/wrench.service';
import { SessionDataProviderService } from 'src/app/store/session-data-provider.service';
import { BlogDataService } from 'src/app/store/blog-data.service';
import { environment} from "../../../environments/environment";
import {AlertController, LoadingController, Platform} from '@ionic/angular';
import { Preferences  } from '@capacitor/preferences';
import { Capacitor } from '@capacitor/core';
import jwt_decode from "jwt-decode";
import {
  SignInWithApple,
  SignInWithAppleResponse,
  SignInWithAppleOptions,
} from '@capacitor-community/apple-sign-in';
import {
  FacebookLogin,
  FacebookLoginResponse,
} from '@capacitor-community/facebook-login';
import { GoogleAuth, User } from '@codetrix-studio/capacitor-google-auth';
import {UserWalletService} from "../../store/user-wallet.service";
import {IntervalRefreshService} from "../../store/interval-refresh.service";
import {MarketDataService} from "../../store/market-data.service";
import {TasksDataService} from "../../store/tasks-data.service";
import {BannersDataService} from "../../store/banners-data.service";

@Component({
  selector: 'app-login',
  templateUrl: './login.page.html',
  styleUrls: ['./login.page.scss'],
})
export class LoginPage implements OnInit {
  @ViewChild('username') username;
  @ViewChild('password') password;

 // @ViewChild('signup_username') signup_username;
  @ViewChild('random_text') random_text;
  @ViewChild('signup_password') signup_password;

  loginResult: any;
  blogResult:any;
  showSocial:boolean = true;
  appleSignInAbortController: any;
  appleSignInWindow: any;
  state: any;
  ios: boolean;
  android: boolean;
  isDisabled:boolean=true;
  isPendingDisabled:boolean=true;
  loginType:string='normal';
  pending_uid:string='';
  signup_country:string='';
  signup_username:string='';

  constructor(
    private router: Router,
    private wrenchService: WrenchService,
    public sessionDataProviderService:SessionDataProviderService,
    public blogDataService:BlogDataService,
    private alertController: AlertController,
    public userWalletService: UserWalletService,
    public intervalRefreshService: IntervalRefreshService,
    public platform: Platform,
    private loadingCtrl: LoadingController,
    public marketDataService:MarketDataService,
    public tasksDataService:TasksDataService,
    public bannersDataService:BannersDataService
  ) {
      this.sessionDataProviderService.DestroySessionOnLogout();
    // https://ionicframework.com/docs/angular/platform
    this.ios = platform.is('ios');
    this.android = platform.is('android'); 
 }

 ionViewDidEnter() {
  // GoogleAuth.init();
  // use hook after platform dom ready
  GoogleAuth.initialize({
    clientId: '817021856543-khlurl8ifdr0sd2cvekn167d02mk9dlg.apps.googleusercontent.com',
    scopes: ['profile', 'email'],
    grantOfflineAccess: true,
  });
 }

  ngOnInit() {
    this.showSocial =  environment.loginSocial;
      //  this.username='ses66181+6018@gmail.com';
      //  this.username='ses66181+1@gmail.com';
      //  this.password='may12002';

      const checkName = async () => {
          const { value } = await Preferences.get({ key: 'username' });
          this.username=value;

          //console.log(`Hello ${value}!`);
      };

    // use hook after platform dom ready
    FacebookLogin.initialize({ appId: environment.facebookAppId });
  }

getBlogData(){
  this.wrenchService.getBlogData([]).subscribe(
    blogResult => {
      this.blogResult = blogResult;
      console.log("BLOG RETURN->", this.blogResult);
      this.blogDataService.setBlogData(this.blogResult.blogdata);
    }
  ); 
}

    refreshBut(){
      this.isDisabled = true;
      if (
          this.username != undefined
          && this.password !=undefined
          && String(this.username).length > 5
          && String(this.password).length > 5
      ){
          this.isDisabled = false;
      }
    }
  loginData: {
    username: string, password: string, sessionid: string
  };
  async startLogin() {
      const loading = await this.loadingCtrl.create({
          message: 'Starting ... ',
          duration: 1500,
      });

    if (this.username == null || this.username == '' || this.validateEmail(this.username) == false || this.password == null || this.password == '') {
      this.showAlert('Invalid Login', 'Enter username(email) and password to login');
      return;
    }
    loading.present();
    this.loginData = { username: this.username, password: this.password, sessionid: 'DUMMY-APP-SESSION' }
    this.wrenchService.loginUser(this.loginData).subscribe(
      loginResult => {
        this.loginResult = loginResult;
        console.log("INTERNAL RETURN->" + this.loginResult.internal_return);
        if (loginResult != null && loginResult.internal_return == 100 && this.sessionDataProviderService.ConstructGlobalSessionData(this.loginResult) == true) {

            const setName = async () => {
                await Preferences.set({
                    key: 'username',
                    value: this.username,
                });
            };


            // this.intervalRefreshService.startIntervalCalls(); // anything with interval call
            // this.marketDataService.getJobsData();
            // this.getBlogData();
            // this.userWalletService.getWallet();
            this.startUpCalls();
            this.router.navigate(['tabs/tab1']);
        }
        else{
           //debugger;
            if (loginResult != null && loginResult.pending_uid != undefined){
                this.loginType='pending';
                this.pending_uid =  loginResult.pending_uid;
                this.signup_username = loginResult.username;
                this.signup_country = loginResult.country;
            }
            else{
                this.showAlert("Error","Invalid username/password");
            }
         // this.showAlert("Error","Invalid username/password");
        }
      }
    );
  }

  async startUpCalls(){
      this.intervalRefreshService.startIntervalCalls(); // anything with interval call
      this.marketDataService.getJobsData();
      this.getBlogData();
      this.tasksDataService.getJobsData();
      this.userWalletService.getWalletData();
      this.bannersDataService.getBannersData();
  }
  onForgot() {
    this.router.navigate(['forgot']);
  }

  onRegister() {
    this.router.navigate(['register']);
  }

  moveToStartScan(){
    this.router.navigate(['startscan']);
  }

    //*************************************************
    // Start Pending Account set up
    //*************************************************
    completeSignupData: {
        action:11010,
        username: string,
        random_text: string,
        password: string,
        pending_uid:string,
        mobile: string,
        sessionid: string
    };
    signUpResult:any;
    onCompleteProfile(){
        this.completeSignupData = {
            action:11010,
            username: this.signup_username,
            random_text: this.random_text,
            password: this.signup_password,
            pending_uid: this.pending_uid,
            mobile: "MOBILE",
            sessionid: "ABOUT-TO_START"
        };
        console.log("COMPLETE SIGNUP ",this.completeSignupData);

        this.wrenchService.completeMobileSignup(this.completeSignupData).subscribe(
            signUpResult => {
                this.signUpResult =  signUpResult;
                if (signUpResult != null && signUpResult.internal_return == 100 && this.sessionDataProviderService.ConstructGlobalSessionData(this.signUpResult) == true) {
                    // this.getBlogData();
                    this. onReturnToLogin();
                    this.router.navigate(['tabs/tab1']);
                }
                else{
                    this. onReturnToLogin();
                    this.showAlert("Sign up error","Unable to complete the sign up, please try again");
                }
            }

        );
    }
    //*************************************************
    // End Pending Account set up
    //*************************************************
    onReturnToLogin(){
      this.loginType='normal';
    }

    signupVerify(){
        this.isPendingDisabled = true;
        if (
            this.signup_username != undefined
            && this.signup_password !=undefined
            && this.random_text != undefined
            && String(this.signup_password).length > 7
            && String(this.signup_password).length < 15
            && String(this.random_text).length > 3
            && String(this.random_text).length < 10
        ){
            this.isPendingDisabled = false;
        }
    }
  onLoginGoogle() {
    GoogleAuth.signIn().then((user: User) => {
      //const credential = auth.GoogleAuthProvider.credential(user.authentication.idToken);
      //return this.afAuth.auth.signInAndRetrieveDataWithCredential(credential);

      if (user) { 
        const oauth2Data = {
          "auth_type": "GOOGLE",
          "access_token": user.authentication.accessToken,
          "refresh_token": user.authentication.refreshToken,
          "idToken": user.authentication.idToken,
          "auth_code": user.serverAuthCode,
          "user": user
        };
        console.log(oauth2Data);
        // Validate token with server and create new session
        this.wrenchService.authStart(oauth2Data).subscribe(
          loginResult => {
            console.log(loginResult);
            this.loginResult = loginResult;
            console.log("INTERNAL RETURN->" + this.loginResult.internal_return);
  
            if (loginResult != null && loginResult.internal_return == 100 && this.sessionDataProviderService.ConstructGlobalSessionData(this.loginResult) == true) {
              const setName = async () => {
                    await Preferences.set({
                        key: 'username',
                        value: this.username,
                    });
              };

                // this.intervalRefreshService.startIntervalCalls(); // anything with interval call
                // this.marketDataService.getJobsData();
                // this.getBlogData();
                // this.userWalletService.getWallet();
                this.startUpCalls();
              this.router.navigate(['tabs/tab1']);
            }
            else{
                this.showAlert("Error","Invalid username/password");
                // debugger;
                // if (loginResult != null && loginResult.pending_uid != undefined){
                //     this.loginType='pending';
                // }
                // else{
                //     this.showAlert("Error","Invalid username/password");
                // }
            }
          }
        ); 
      } else {
        console.log(user);
        this.showAlert("Error", "Login failed!");      
      }
    }).catch((error: any) => {
      this.showAlert("Error", error);
      console.log(error);
    });
  }

  onLoginFacebook() {
    const FACEBOOK_PERMISSIONS = [
      'email',
      'user_birthday',
      'user_photos',
      'user_gender',
    ];

    FacebookLogin.login({ 
      permissions: FACEBOOK_PERMISSIONS 
    }).then((result: FacebookLoginResponse) => {
      if (result.accessToken) {
        // Login successful.
        console.log(result);
        console.log(`Facebook access token is ${result.accessToken.token}`);

        /*
        var reqData = {
          auth_type: "FACEBOOK",
          code: codeResponse,
          redirect_uri: process.env.REACT_APP_FACEBOOK_REDIRECT_URL,
        };
        */
        const oauth2Data = {
          "auth_type": "FACEBOOK",
          "access_token": result.accessToken.token,
          "user":result.accessToken.userId,
          "application_id":result.accessToken.applicationId,
        };
        console.log(oauth2Data);
        // Validate token with server and create new session
        this.wrenchService.authStart(oauth2Data).subscribe(
          loginResult => {
            console.log(loginResult);
            this.loginResult = loginResult;
            console.log("INTERNAL RETURN->" + this.loginResult.internal_return);

            if (loginResult != null && loginResult.internal_return == 100 && this.sessionDataProviderService.ConstructGlobalSessionData(this.loginResult) == true) {
              const setName = async () => {
                    await Preferences.set({
                        key: 'username',
                        value: this.username,
                    });
              };

                // this.intervalRefreshService.startIntervalCalls(); // anything with interval call
                // this.marketDataService.getJobsData();
                // this.getBlogData();
                // this.userWalletService.getWallet();
                this.startUpCalls();
              this.router.navigate(['tabs/tab1']);
            }
            else{
              this.showAlert("Error","Invalid username/password");
            }
          }
        );

      } else {
        console.log(result);
        this.showAlert("Error", "Login failed!");
      }
    }).catch((error: any) => {
      this.showAlert("Error", error);
      console.log(error);
    });
  }

  onLoginApple() {

    // -> 'web', 'ios' or 'android'
    if (Capacitor.getPlatform() === 'web') {
      this.appleSignInAbortController = new AbortController();
      this.appleSignInWindow = window.open(
        'https://appleid.apple.com/auth/authorize?' +
          'client_id=com.wrenchboard.users&'+
          'redirect_uri='+environment.appleRedirectUri+'&' +
          'response_type=code id_token&' +
          'scope=name email&' +
          'response_mode=web_message',
        '_blank'
      );
      window.addEventListener(
        'message',
        (e) => {this.appleTokenReceived(e);},
        {signal: this.appleSignInAbortController.signal}
      );
      return;
    }
    console.log("Capacitor platfor: " + Capacitor.getPlatform());
    const rawNonce = (Math.random() + 1).toString(36);
    //const nonce = shajs('sha256').update(rawNonce).digest('hex');
    const nonce = rawNonce;   
    this.state = (Math.random() + 1).toString(36);

    let options: SignInWithAppleOptions = {
      clientId: 'com.wrenchboard.users',
      redirectURI: environment.appleRedirectUri,
      scopes: 'email name',
      state: '12345', /* this.state, */
      nonce: nonce,
    };

    // https://developer.okta.com/blog/2019/06/04/what-the-heck-is-sign-in-with-apple
  
    SignInWithApple.authorize(options)
    .then((result: SignInWithAppleResponse) => {
      // Handle user information
      console.log("response", result.response);
      /*
      {
        "identityToken":"eyJraWQiOiJZdXlYb1kiLCJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJodHRwczovL2FwcGxlaWQuYXBwbGUuY29tIiwiYXVkIjoiY29tLndyZW5jaGJvYXJkLnVzZXJzIiwiZXhwIjoxNjk0MzkzMzE3LCJpYXQiOjE2OTQzMDY5MTcsInN1YiI6IjAwMTgxMC4yMGU3NTAyOGQ0OWM0MmQ4YjQzMGI0MmQxZDc0ODdmMy4xMTU3Iiwibm9uY2UiOiIxLnB1ZmJwZGFhMzYiLCJjX2hhc2giOiJQRE1PNXNGa2pjOEtPclNNZDRjUGZnIiwiZW1haWwiOiJhY2lkdW1pcmFlQGdtYWlsLmNvbSIsImVtYWlsX3ZlcmlmaWVkIjoidHJ1ZSIsImF1dGhfdGltZSI6MTY5NDMwNjkxNywibm9uY2Vfc3VwcG9ydGVkIjp0cnVlLCJyZWFsX3VzZXJfc3RhdHVzIjoyfQ.fEnzaVgB2JaOZbQm2fkpC_J8if5tIIfAphQptZ9Bxp2wrjnDsGvN1b0gvB3KBswv7d6n4A1U46GpaGpShJDhN-e2lKw_lzgFJlRi9-1B-Fudp_gzK61r6W8JzzbPiD0GZgfp_ITPDdxdC7hzixVx4TW8djrV4TIXYjus0b5XnzqRVz2t3ed4Et55s_SZ53SVhM9qnDruVB-KgeGrvDVUks71iM1etuP2vO3xsSFoiKfMEcankX3JUJaCNRSdvVVeUBqH9TfhvmHrCopjnlJ8N2B8o8RDhbnt99OAJtE_dw_Qt5YAAg2ITYQVLBb2dniJ5FBsOBBwbiA0-W1hPJ3RpQ","authorizationCode":"ce0061e5858a34e468a373c3ea7344cdb.0.rryrq.rK6JjdqlVVi6S9coEcTgVQ",
        "email":null,
        "givenName":null,
        "familyName":null,
        "user":"001810.20e75028d49c42d8b430b42d1d7487f3.1157"
      }
      */
      // result.response.user
      // result.response.identityToken
      // result.response.email: null
      // result.response.givenName: null
      // result.response.familyName: null

      var decoded = jwt_decode(result.response.identityToken);

      // https://developer.apple.com/documentation/sign_in_with_apple/sign_in_with_apple_rest_api/authenticating_users_with_sign_in_with_apple
      console.log(decoded);
      /*
      {
        "iss": "https://appleid.apple.com",
        "aud": "com.wrenchboard.users",
        "exp": 1694393317,
        "iat": 1694306917,
        "sub": "001810.20e75028d49c42d8b430b42d1d7487f3.1157",
        "nonce": "1.pufbpdaa36",
        "c_hash": "PDMO5sFkjc8KOrSMd4cPfg",
        "email": "acidumirae@gmail.com",
        "email_verified": "true",
        "auth_time": 1694306917,
        "nonce_supported": true,
        "real_user_status": 2
      }
      */
      // real_user_status => The possible values are: 0 (or Unsupported), 1 (or Unknown), 2 (or LikelyReal).

      const oauth2Data = {
        "auth_type": "APPLE",
        "identityToken": result.response.identityToken,
        "email":result.response.email,
        "givenName":result.response.givenName,
        "familyName":result.response.familyName,
        "user":result.response.user,
        "authorizationCode":result.response.authorizationCode,
        "sub": decoded["sub"],
        "jwt_email": decoded["email"],
        "email_verified": decoded["email_verified"],
        "real_user_status": decoded["real_user_status"]
      };
      //console.log(oauth2Data);

      this.username = decoded["email"] ?? result.response.email;

      // Validate token with server and create new session
      this.wrenchService.authStart(oauth2Data).subscribe(
        loginResult => {
          console.log(loginResult);
          this.loginResult = loginResult;
          console.log("INTERNAL RETURN->" + this.loginResult.internal_return);
          /*
          localStorage.setItem("member_id", `${loginResult.data.member_id}`);
          localStorage.setItem("uid", `${loginResult.data.uid}`);
          localStorage.setItem("session_token", `${loginResult.data.session}`);
          dispatch(updateUserDetails({...loginResult.data}));
          */
          if (loginResult != null && loginResult.internal_return == 100 && this.sessionDataProviderService.ConstructGlobalSessionData(this.loginResult) == true) {
              const setName = async () => {
                  await Preferences.set({
                      key: 'username',
                      value: this.username,
                  });
              };

              // this.intervalRefreshService.startIntervalCalls(); // anything with interval call
              // this.marketDataService.getJobsData();
              // this.getBlogData();
              // this.userWalletService.getWallet();
              this.startUpCalls();
            this.router.navigate(['tabs/tab1']);
          }
          else{
            this.showAlert("Error","Invalid username/password");
          }
        }
      );
    })
    .catch((error) => {
      this.showAlert("Error", error);
      console.log(error);
    });
    console.log("onLoginApple() out");
  }

  appleTokenReceived(event: any) {
    console.log(event);
    this.appleSignInAbortController.abort();
    this.appleSignInWindow.close();
    if (!(event instanceof MessageEvent)) {
      return;
    }
    const data = JSON.parse(event.data);
    if (typeof data !== 'object' || data === null) {
      return;
    }
    if (data.data.hasOwnProperty('error')) {
      return;
    }
    let postData: any = {
      token: data.data.authorization.id_token,
      device_id: 'device UUID', /** NOT IMPLEMENTED! */
    };
    if (
      data.data.hasOwnProperty('user') &&
      data.data.user.hasOwnProperty('name') &&
      data.data.user.name.hasOwnProperty('firstName') &&
      data.data.user.name.hasOwnProperty('lastName')
    ) {
      //this is only filled after the first login of the user
      postData.name = data.data.user.name.lastName + ' ' + data.data.user.name.firstName;
    }
    //this.http.post(environment.appleRedirectUri + '/api/auth/loginWithApple', postData).subscribe(//Do whatever you need with the data);
    this.showAlert("Error", "appleTokenReceived is not implemented!");
  }

  onClick() {
    this.router.navigate(['slider']);
  }

  validateEmail(email) {
    var re = /\S+@\S+\.\S+/;
    return re.test(email);
  }

    async showAlert(mtitle: string, amessage: string) {

      const alert = await this.alertController.create({
          header: 'WrenchBoard',
          subHeader: mtitle,
          message: amessage,
          buttons: ['OK'],
      });

      await alert.present();
  //
  //    let alert = this.alertCtrl.create({
  //      title: mtitle,
  //      subTitle: amessage,
  //      buttons: ['OK']
  //    });
  //    alert.present();
  // //  alert(amessage);
  }
  familyLogin(){
    this.router.navigate(['familylogin']);
  }

/*
const setName = async () => {
    await Preferences.set({
        key: 'name',
        value: 'Max',
    });
};

const checkName = async () => {
    const { value } = await Preferences.get({ key: 'name' });

    console.log(`Hello ${value}!`);
};

const removeName = async () => {
    await Preferences.remove({ key: 'name' });
};

*/

}
