/*
	Licensed Material - Property of IBM

	(C) Copyright 2015, 2016 IBM Corp.

	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License.
*/


'use strict';

var serverSupport = require('mdo-server-support');
var Q = require('q');

module.exports.configureConfidentialClients = function(appJson, serverInfo) {
    var deferred = Q.defer();

    if (appJson.confidentialClients) {
      serverSupport.getConfidentialClients(serverInfo).then(function(result) {
        var finalClients = [];

        for (var curIndex = 0; curIndex < result.clients.length; curIndex++) {
          var found = false;
          var currentClient = result.clients[curIndex];
          for (var index = 0; index < appJson.confidentialClients.length; index++) {
            if (appJson.confidentialClients[index].id == currentClient.id) {
              found = true;
              break;
            }
          }
          if (!found) {
            if (currentClient.customconfclient) {
              delete currentClient.customconfclient;
            }
            finalClients.push(currentClient);
          }
        }

        appJson.confidentialClients.forEach(function(client) {
          if (client.customconfclient) {
            delete client.customconfclient;
          }          
          finalClients.push(client);
        })

        serverSupport.putConfidentialClients(serverInfo, { clients: finalClients }).then(function() {
          deferred.resolve();
        }).catch(function(err) {
          deferred.reject(err);
        });
      }).catch(function(err) {
        deferred.reject(err);
      });  
    } else {
      deferred.resolve();
    }   

    return deferred.promise;
}