/*
 * Copyright (c) 2018-2019, FusionAuth, All Rights Reserved
 */
'use strict';

var FusionAuth = FusionAuth || {};
FusionAuth.IdentityProvider = FusionAuth.IdentityProvider || {};

/**
 * @constructor
 */
FusionAuth.IdentityProvider.Facebook = function() {
  Prime.Utils.bindAll(this);

  Prime.Document.onReady(function() {
    this.button = Prime.Document.queryById('facebook-login-button');
    this.scope = this.button.getDataAttribute('permissions');
    Prime.Document.addDelegatedEventListener('click', '#facebook-login-button', this._handleLoginClick);
  }.bind(this));

  // Load the appId
  var scripts = document.getElementsByTagName('script');
  var lastScript = new Prime.Document.Element(scripts[scripts.length-1]);
  window.fbAsyncInit = function() {
    FB.init({
      appId: lastScript.getDataAttribute('appId'),
      cookie: true,
      status: true,
      version: 'v3.1',
      xfbml: false
    });

    var automaticFacebookLogin = false;
    if (automaticFacebookLogin) {
      FB.getLoginStatus(function(response) {
        this._loginCallback(response);
      }.bind(this));
    }

  }.bind(this);
};

FusionAuth.IdentityProvider.Facebook.constructor = FusionAuth.IdentityProvider.Facebook;
FusionAuth.IdentityProvider.Facebook.prototype = {

  /* ===================================================================================================================
   * Private methods
   * ===================================================================================================================*/

  _handleLoginClick: function(event) {
    Prime.Utils.stopEvent(event);

    FB.getLoginStatus(function(response) {
      if (response.status === "connected") {
        this._loginCallback(response);
      } else {
        FB.login(function(response) {
          if (response.authResponse) {
            this._loginCallback(response);
          } else {
            console.log('User cancelled login or did not fully authorize.');
          }
        }.bind(this), {
          scope: this.scope
        });
      }
    }.bind(this));
  },

  _loginCallback: function(response) {
    if (response.status === 'connected') {
      var state =  encodeURIComponent(
          'client_id=' + encodeURIComponent(Prime.Document.queryFirst('input[name=client_id]').getValue())
          + '&metaData.device.name=' + encodeURIComponent(Prime.Document.queryFirst('input[name="metaData.device.name"]').getValue())
          + '&metaData.device.type=' + encodeURIComponent(Prime.Document.queryFirst('input[name="metaData.device.type"]').getValue())
          + '&nonce=' + encodeURIComponent(Prime.Document.queryFirst('input[name="nonce"]').getValue())
          + '&redirect_uri=' + encodeURIComponent(Prime.Document.queryFirst('input[name=redirect_uri]').getValue())
          + '&response_type=' + encodeURIComponent(Prime.Document.queryFirst('input[name=response_type]').getValue())
          + '&scope=' + encodeURIComponent(Prime.Document.queryFirst('input[name=scope]').getValue())
          + '&state=' + encodeURIComponent(Prime.Document.queryFirst('input[name=state]').getValue())
          + '&timezone=' + encodeURIComponent(Prime.Document.queryFirst('input[name=timezone]').getValue())
      );

      window.location.href = '/oauth2/callback'
          + '?token=' + encodeURIComponent(response.authResponse.accessToken)
          + '&identityProviderId=56abdcc7-8bd9-4321-9621-4e9bbebae494'
          + '&state=' + state;

    } else if (response.status === 'not_authorized') {
      console.log('Not Authorized');
    } else {
      console.log('Unknown');
    }
  }
};

// Create the singleton instance
FusionAuth.IdentityProvider.Facebook.instance = new FusionAuth.IdentityProvider.Facebook();