import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { NbAuthResult, NbAuthService } from '@nebular/auth';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { environment } from '../../../environments/environment';
declare var gapi: any;
declare var google: any;
@Component({
  selector: 'ngx-google-login',
  templateUrl: './google-login.component.html',
  styleUrls: ['./google-login.component.scss']
})
export class GoogleLoginComponent implements OnInit {

  private destroy$ = new Subject<void>();
  constructor(
    private authService: NbAuthService,
    private router: Router
  ) {

  }

  ngOnInit(): void {

    if (this.router.url.endsWith('googleLoginCallback')) {
      this.authService.authenticate('google')
        .pipe(takeUntil(this.destroy$))
        .subscribe((authResult: NbAuthResult) => {
          if (authResult.isSuccess()) {
            this.router.navigateByUrl('/pages/dashboard');
          }
        });
    } else {

      // gapi.signin2.render('my-signin2', {
      //   'scope': 'profile email',
      //   'width': 240,
      //   'height': 50,
      //   'longtitle': true,
      //   'theme': 'dark',
      //   // 'onsuccess': onSuccess,
      //   // 'onfailure': onFailure
      // });

      // google.accounts.id.initialize({
      //   client_id: environment.GAPI_CLIENT_ID,
      //   callback: 'http://localhost:4200/CellGroup/googleLoginCallback'
      // });
      // google.accounts.id.renderButton(
      //   document.getElementById("buttonDiv"),
      //   { theme: "outline", size: "large" }  // customization attributes
      // );
      // google.accounts.id.prompt(); // also display the One Tap dialog
    }
  }
  googleLoginCallback(response) {

  }
  ngOnDestroy(): void {
    this.destroy$.next();
    this.destroy$.complete();
  }
  initGoogleOAuth(): Promise<any> {
    return new Promise((resolve, reject) => {
      gapi.load('auth2', async () => {
        const gAuth = await gapi.auth2.init({
          client_id: environment.GAPI_CLIENT_ID,
          fetch_basic_profile: true,
          scope: 'profile email'
        });

        console.log('google ClientId', environment.GAPI_CLIENT_ID);
        resolve(gAuth);
      }, reject);
    });
  }
  login() {
    this.authService.authenticate('google')
      .pipe(takeUntil(this.destroy$))
      .subscribe((authResult: NbAuthResult) => {
        console.log('google login', authResult);
        console.log('google getResponse', authResult.getResponse());
        console.log('google getToken.getName', authResult.getToken().getName());
        console.log('google getToken.getOwnerStrategyName', authResult.getToken().getOwnerStrategyName());
        console.log('google getToken.getPayload', authResult.getToken().getPayload());
        console.log('google getToken.getValue', authResult.getToken().getValue());
        //`https://www.googleapis.com/oauth2/v2/userinfo?access_token=${authResult.getToken().getValue()}`
        //https://www.googleapis.com/oauth2/v2/userinfo?access_token=
      });
  }
  onSignIn(googleUser) {
    var profile = googleUser.getBasicProfile();
    console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
    console.log('Name: ' + profile.getName());
    console.log('Image URL: ' + profile.getImageUrl());
    console.log('Email: ' + profile.getEmail()); // This is null if the 'email' scope is not present.
  }

}
