import { Component, OnInit } from '@angular/core';
import { 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 { FacebookLogin, FacebookLoginResponse } from '@capacitor-community/facebook-login';
import { GoogleAuth } from '@codetrix-studio/capacitor-google-auth';
import { Browser } from '@capacitor/browser';


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

  private loading: any;

  constructor(
    private authService: AuthService,
    private navCtrl: NavController,
    private alertService: AlertService,
    private translateService: TranslateService,
    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');
  }

  async login(form: NgForm) {
    this.loading = await this.loadingCtrl.create();
    await this.loading.present();

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

  async loginFacebook() {
      this.loading = await this.loadingCtrl.create();
      await this.loading.present();

      try {
        // Login with permissions
        const result = await FacebookLogin.login({ permissions: ['public_profile', 'email'] });

        if (result.accessToken) {
          // Get user ID and Token
          const fb_id = result.accessToken.userId;
          const fb_token = result.accessToken.token;

          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'));
            }
          );
        } 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);
      }
  }

  async loginGoogle() {
    this.loading = await this.loadingCtrl.create();
    await this.loading.present();

    try {
      const res = await GoogleAuth.signIn();
      console.log(res);

      const google_id = res.id;
      const google_token = res.authentication.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);
    }
  }

  async openTerms() {
    await Browser.open({ url: 'https://jobheroapp.com/terminos-y-condiciones' });
  }
}
