import { Component, OnInit } from '@angular/core';
import { UserService } from '../../services/user.service';

// For capacitor Facebook
import { Platform } from '@ionic/angular';
import { Plugins, registerWebPlugin } from '@capacitor/core';
import { HttpClient } from '@angular/common/http';
import { FacebookLoginPlugin } from '@capacitor-community/facebook-login';
import { FacebookLogin } from '@capacitor-community/facebook-login';
registerWebPlugin(FacebookLogin);
const { App } = Plugins;

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

    fbLogin: FacebookLoginPlugin;
    user = null;
    token = null;

    hideAll: boolean = false;

    showLogout: boolean = false;

    constructor(
        private platform: Platform,
        private http: HttpClient,
        private userService: UserService
    ) {        
    }

    ngAfterViewInit() {
        this.setupFbLogin();        
    }

    ngOnInit() {
        
    }

    async setupFbLogin() {
        if (this.platform.is('android') || this.platform.is('capacitor')) {            
            // Use the native implementation inside a real app!
            const { FacebookLogin } = Plugins;
            this.fbLogin = FacebookLogin;

            if (localStorage.getItem('FBUser') && localStorage.getItem('FBToken')) {
                this.user = JSON.parse(localStorage.getItem('FBUser'));
                this.getCurrentToken();
            }

        } else {
            this.hideAll = true;
        }        
    }

    async login() {
        const FACEBOOK_PERMISSIONS = ['email'];
        const result = await this.fbLogin.login({ permissions: FACEBOOK_PERMISSIONS });
     
        if (result.accessToken && result.accessToken.userId) {
            this.token = result.accessToken;
            this.loadUserData();
            
            localStorage.setItem('FBToken', this.token);

        } else if (result.accessToken && !result.accessToken.userId) {
            // Web only gets the token but not the user ID
            // Directly call get token to retrieve it now
            this.getCurrentToken();
        } else {
            // Login failed
            alert("Login Failed");
        }
    }

    async getCurrentToken() {
        const result = await this.fbLogin.getCurrentAccessToken();
        
        if (result.accessToken) {
            this.token = result.accessToken;
            this.loadUserData();

            localStorage.setItem('FBToken', JSON.stringify(this.token));


            this.userService.getUserProfile().then((data) => {
                localStorage.setItem('ServerUserData', JSON.stringify(data));
            }, err => alert(JSON.stringify(err)));

        } else {
            // Not logged in.
        }
    }
        
    async loadUserData() {
        const url = `https://graph.facebook.com/${this.token.userId}?fields=id,name,picture.width(720),email&access_token=${this.token.token}`;
        this.http.get(url).subscribe(res => {
            this.user = res;
            localStorage.setItem('FBUser', JSON.stringify(res));
        }, (err) => {
            console.log(JSON.stringify(err));
            alert("Falied to fetch user data");
        });
    }
        
    async logout() {
        await this.fbLogin.logout().then(() => {
            console.log("Logged Out");
        }, (err) => alert(JSON.stringify(err)));
        this.user = null;
        this.token = null;
        localStorage.removeItem('FBUser');
        localStorage.removeItem('FBToken');
        localStorage.removeItem('ServerUserData');
        App.exitApp();
    }

}
