import { Component, OnInit } from '@angular/core';
import { ModalController, NavController, LoadingController } from '@ionic/angular';
import { NgForm } from '@angular/forms';
import { AuthService } from 'src/app/services/auth.service';
import { AlertService } from 'src/app/services/alert.service';
import { TranslateService } from '@ngx-translate/core';
import { Facebook, FacebookLoginResponse } from '@ionic-native/facebook/ngx';
import { GooglePlus } from '@ionic-native/google-plus/ngx';
import { InAppBrowser } from '@ionic-native/in-app-browser/ngx';


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

  private loading;

  constructor(
    private modalController: ModalController,
    private authService: AuthService,
    private navCtrl: NavController,
    private alertService: AlertService,
    private translateService: TranslateService,
    private fb: Facebook,
    private googlePlus: GooglePlus,
    private iab: InAppBrowser,
    private loadingCtrl: LoadingController
  ) { }
  ngOnInit() {
  }
  // Dismiss Login Modal
  dismissLogin() {
    this.navCtrl.navigateRoot('/landing');
  }
  // On Register button tap, dismiss login modal and open register modal
  registerModal() {
    this.navCtrl.navigateForward('/register');
  }

  // On Forgot text tap, dismiss login modal and open forgot modal
  forgotModal() {
    this.navCtrl.navigateForward('/forgot');
  }

  login(form: NgForm) {
    this.loadingCtrl.create().then((overlay) => {
      this.loading = overlay;
      this.loading.present();
    });
    this.authService.login(form.value.email, form.value.password).subscribe(
      data => {
        this.loading.dismiss();
      },
      error => {
        if (JSON.stringify(error['status']) == '401') {
          this.loading.dismiss();
          this.alertService.presentToast(this.translateService.instant('alerts.login_error'));
        }
        else {
          this.loading.dismiss();
          this.alertService.presentToast(this.translateService.instant('alerts.error') + error['message']);
          console.log(error);
        }
      },
      () => {
        this.dismissLogin();
        this.navCtrl.navigateRoot('/dashboard');
        this.alertService.presentToast(this.translateService.instant('alerts.login'));
      }
    );
  }

  loginFacebook() {
      this.loadingCtrl.create().then((overlay) => {
        this.loading = overlay;
        this.loading.present();
      });
      // Login with permissions
      this.fb.login(['public_profile', 'email'])
      .then( (res: FacebookLoginResponse) => {

          // The connection was successful
          if(res.status == "connected") {

              // Get user ID and Token
              var fb_id = res.authResponse.userID;
              var fb_token = res.authResponse.accessToken;

              console.log("ID: " + fb_id);
              console.log("Token: " + fb_token);

              this.authService.login_register_fb(fb_token, fb_id).subscribe(
                data => {
                },
                error => {
                  this.loading.dismiss();
                  this.alertService.presentToast(this.translateService.instant('alerts.error') + error);
                  console.log(error);
                },
                () => {
                  this.loading.dismiss();
                  this.dismissLogin();
                  this.navCtrl.navigateRoot('/dashboard');
                  this.alertService.presentToast(this.translateService.instant('alerts.login'));
                }
              );

          }
          // An error occurred while loging-in
          else {
              this.loading.dismiss();
              this.alertService.presentToast(this.translateService.instant('alerts.timeout_error'));
          }

      })
      .catch((e) => {
          this.loading.dismiss();
          this.alertService.presentToast(this.translateService.instant('alerts.error') + e);
      });
  }

  loginGoogle() {
    this.loadingCtrl.create().then((overlay) => {
      this.loading = overlay;
      this.loading.present();
    });
    // Login with permissions
      this.googlePlus.login({})
      .then(res => {
        console.log(res);

        var google_id = res.userId;
        var google_token = res.accessToken;

        console.log("ID: " + google_id);
        console.log("Token: " + google_token);

        this.authService.login_register_googlePlus(google_token, google_id).subscribe(
          data => {
          },
          error => {
            this.loading.dismiss();
            this.alertService.presentToast(this.translateService.instant('alerts.error') + error);
            console.log(error);
          },
          () => {
            this.loading.dismiss();
            this.dismissLogin();
            this.navCtrl.navigateRoot('/dashboard');
            this.alertService.presentToast(this.translateService.instant('alerts.login'));
          }
        );

      })
      .catch(err => {
        this.loading.dismiss();
        this.alertService.presentToast(this.translateService.instant('alerts.error') + err);
        console.log(err);
      });
  }

  openTerms() {
    this.iab.create('https://jobheroapp.com/terminos-y-condiciones', '_system')
  }
}
