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

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

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

  // Load the client id
  var scripts = document.getElementsByTagName('script');
  var lastScript = new Prime.Document.Element(scripts[scripts.length - 1]);
  this.clientId = lastScript.getDataAttribute('clientId');

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

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

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

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

    var state = encodeURIComponent(
        'client_id=' + encodeURIComponent(Prime.Document.queryFirst('input[name=client_id]').getValue())
        + '&identityProviderId=45bb233c-0901-4236-b5ca-ac46e2e0a5a5'
        + '&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 = '/oauth1/request-token?'
        + 'state.client_id=' + this.clientId
        + '&state.state=' + state
        + '&state.identityProviderId=45bb233c-0901-4236-b5ca-ac46e2e0a5a5';
  }
};

FusionAuth.IdentityProvider.Twitter.instance = new FusionAuth.IdentityProvider.Twitter();