import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams,Events } from 'ionic-angular';
import { Facebook, FacebookLoginResponse } from '@ionic-native/facebook';
import { GooglePlus } from '@ionic-native/google-plus';
import { Myservice } from '../../providers/myservice'
import { Storage } from '@ionic/storage';
import { fireService } from "../../providers/firebase.service";
import { Geolocation } from '@ionic-native/geolocation';

@IonicPage()
@Component({
  selector: 'page-landing',
  templateUrl: 'landing.html',
})
export class LandingPage {
  fb_data = { email: '', firstname: '', lastname: '', gender: '', image: '', fb_id: '', id: '', name: '' };
  gp_data = { email: '', firstname: '', lastname: '', image: '', google_id: '', id: '', name: '' };

  constructor(public navCtrl: NavController, public navParams: NavParams, private fb: Facebook, private googlePlus: GooglePlus, private myservice: Myservice, public storage: Storage, private events: Events, private firebase: fireService, private geolocation: Geolocation) {
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad LandingPage');
  }

  open_page(page){
    this.navCtrl.push(page);
  }

  signInWithFB() {
    this.myservice.show_loader()
    this.fb.login(['public_profile', 'user_friends', 'email'])
      .then((res: FacebookLoginResponse) => {
        // console.log('Logged into Facebook!', res)
        this.fb.api('me?fields=id,name,email,gender,last_name,first_name,picture.width(720).height(720).as(picture_large)', []).then(profile => {
          console.log('profile', profile)
          this.fb_data.email = profile.email;
          this.fb_data.name = profile.first_name + ' ' + profile.last_name;
          this.fb_data.image = profile.picture_large.url;
          // this.fb_data.fb_id = profile.id;
          this.myservice.load_post(this.fb_data, 'social_login').subscribe(response => {
            if (response.status == true) {
              this.getLoc().then((obj: any) => {
                var data = response.data
                data.lat = obj.loc.latitude
                data.lng = obj.loc.longitude
                this.firebase.pushItem('users/', response.data)
                response.data.image = response.data.image.startsWith("http") ? response.data.image : this.myservice.base_url + response.data.image;
                this.myservice.hide_loader()
              this.storage.set('user_data', response.data);
              this.logged_event(this.fb_data)
              this.navCtrl.setRoot('HomePage')
              })
            }
            else {
            }
          })
        });
      })
      .catch(e => console.log('Error logging into Facebook', e));

  }

  signInWithGoogle() {
    this.myservice.show_loader()
    this.googlePlus.login({})
      .then(res => {
        this.gp_data.email = res.email;
        this.gp_data.name = res.givenName + ' ' + res.familyName;
        if (res.imageUrl) {
          this.gp_data.image = res.imageUrl;
        }
        this.myservice.load_post(this.gp_data, 'social_login').subscribe(response => {
          if (response.status == 'success') {
             this.getLoc().then((obj:any)=>{
              var data = response.data
               data.lat = obj.loc.latitude
               data.lng = obj.loc.longitude
               this.firebase.pushItem('users/', response.data)
               response.data.image = response.data.image.startsWith("http") ? response.data.image : this.myservice.base_url + response.data.image;
              this.myservice.hide_loader()
              this.storage.set('user_data', response.data);
              this.logged_event(response.data)
              this.navCtrl.setRoot('HomePage')
            })
          }
          else {
          }
        })

      })
      .catch(err => console.error(err));
  }

  logged_event(data) {
    this.events.publish('user:profile', data);
  }

  getLoc(){
    var promise = new Promise((resolve, reject) => {
      this.geolocation.getCurrentPosition().then((resp) => {
        resolve({ 'loc': resp.coords });
       })
    });
    return promise;
  }

}
