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

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

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

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

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

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

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

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

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

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