/*
	Licensed Material - Property of IBM

	(C) Copyright 2015 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 log = require('npmlog');
var Q = require('q');
var async = require('async');
var consts = require('./constants');

log.level = global.MDO_CLI_LOG_LEVEL ? global.MDO_CLI_LOG_LEVEL : log.level;

module.exports.run = function(appDetails, configDetails) {
  var deferred = Q.defer();
  var platformTypes = {};
  const results = [];
  var nativePlatformExtensions = getNativePlatformExtensions();  

  if (nativePlatformExtensions) {
    nativePlatformExtensions.forEach(function(platformExtension){
      var platformExtensioneName = platformExtension.name;
      platformTypes[platformExtensioneName] =
        {
          "run": platformExtension.export.run,
        };
    });
    log.verbose(consts.LOG_PREFIX, 'Supported platforms ' + JSON.stringify(platformTypes));
  }

  async.forEachSeries(appDetails.platforms, function (platform, callback) {
    platformTypes[platform].run(appDetails, configDetails, callback).then(function(result) {
      results.push(result);
      callback();
    }).catch(function (error) {   
      callback(error);
    })    
  }, function(err) {
    if (err) {
      deferred.reject(err);
    } else {
      deferred.resolve(results);
    }
  });

  return deferred.promise;
};

function getNativePlatformExtensions() {
  var _nativePlatformExtensions;

  if (!_nativePlatformExtensions) {
    var findExtensions = require('pluggington');

    _nativePlatformExtensions = findExtensions(global.MDO_MAIN_EXTENSIONS_PATH, 'mdo.cli.app.create.native.platform');
  }

  return _nativePlatformExtensions;
}
