'use strict';

var njwt = require('njwt');
var uuid = require('node-uuid');

function SamlIdpUrlBuilder(application) {
  this.application = application;
  this.apiKey = application.dataStore.requestExecutor.options.client.apiKey;
}

SamlIdpUrlBuilder.prototype._getServiceProvider = function _getServiceProvider(callback) {
  this.application.getSamlPolicy(function (err, samlPolicy) {
    if (err) {
      return callback(err);
    }

    samlPolicy.getServiceProvider(callback);
  });
};

SamlIdpUrlBuilder.prototype._buildInitializationUrl = function _buildInitializationUrl(initEndpointUrl, accessToken) {
  return initEndpointUrl + '?accessToken=' + encodeURIComponent(accessToken);
};

SamlIdpUrlBuilder.prototype.build = function (callback) {
  var self = this;
  var apiKey = this.apiKey;

  this._getServiceProvider(function (err, serviceProvider) {
    if (err) {
      return callback(err);
    }

    var accessToken = njwt.create({
      jti: uuid(),
      iss: self.application.href,
      iat: new Date().getTime() / 1000
    }, apiKey.secret);

    accessToken.header.kid = apiKey.id;

    var ssoInitiationEndpoint = serviceProvider.ssoInitiationEndpoint.href;
    var initializationUrl = self._buildInitializationUrl(ssoInitiationEndpoint, accessToken.compact());

    callback(null, initializationUrl);
  });
};

module.exports = SamlIdpUrlBuilder;

@@ -68,16 +68,58 @@
 -uuid');
+%0Avar querystring = require('querystring');
 %0A%0Afuncti
@@ -630,27 +630,26 @@
 intUrl, 
-accessToken
+parameters
 ) %7B%0A  re
@@ -677,54 +677,44 @@
 + '?
-accessToken=' + encodeURIComponent(accessToken
+' + querystring.stringify(parameters
 );%0A%7D
@@ -762,27 +762,179 @@
 nction (
-callback) %7B
+/* %5Boptions,%5D callback */) %7B%0A  var args = Array.prototype.slice.call(arguments);%0A  var callback = args.pop();%0A  var options = args.length %3E 0 ? args.shift() : %7B%7D;%0A
 %0A  var s
@@ -1278,16 +1278,105 @@
 ey.id;%0A%0A
+    var parameters = options %7C%7C %7B%7D;%0A    parameters.accessToken = accessToken.compact();%0A%0A
     var 
@@ -1523,37 +1523,26 @@
 dpoint, 
-accessToken.compact()
+parameters
 );%0A%0A    

add option to add optional query params