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

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

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

  Prime.Document.addDelegatedEventListener('click', '.openid.login-button', this._handleLoginClick);
  Prime.Document.addDelegatedEventListener('click', '.samlv2.login-button', this._handleLoginClick);
};

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

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

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

    var button = new Prime.Document.Element(target);
    var identityProviderId = button.getDataAttribute('identityProviderId');

    var state = encodeURIComponent(
        'client_id=' + encodeURIComponent(Prime.Document.queryFirst('input[name=client_id]').getValue())
        + '&identityProviderId=' + encodeURIComponent(identityProviderId)
        + '&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/redirect?"
        + '&client_id=' + Prime.Document.queryFirst('input[name=client_id]').getValue()
        + '&identityProviderId=' + identityProviderId
        + '&state=' + state;
  }
};

Prime.Document.onReady(function() {
  FusionAuth.IdentityProvider.Redirect.instance = new FusionAuth.IdentityProvider.Redirect();
}.bind(this));
