/*
	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';

//private
var errors = require('mdo-errors');
var findExtensions = require('pluggington');
//public
var log = require('npmlog');
var path = require('path');
var Q = require('q');

var moduleName = 'detectPlatforms';

module.exports = function () {
    var deferred = Q.defer();
    var detectPromises = [];
    var platforms = [];
    var detectPlatformExtensions = findExtensions(global.MDO_MAIN_EXTENSIONS_PATH, 'mdo.platforms');

    log.verbose(moduleName, 'detecting platforms present');
    if(detectPlatformExtensions) {
        detectPlatformExtensions.forEach(function (extension) {
            detectPromises.push(extension.export.detect());
        });

        //If platform was detected the result for that promise is the retObj
        //Else promise is rejected
        Q.allSettled(detectPromises)
        .then(function (results) {
            var retObj;
            results.forEach(function (result) {
                if (result.state === "fulfilled") {
                    platforms.push(result.value);
                }
            });

            platforms = processPossibleMultipleProjects(platforms);

            if(platforms.length > 0) {
                retObj = {
                    isCordova: platforms[0].configXMLPath !== undefined ? true : false,
                    rootDir: platforms[0].configXMLPath !== undefined ? path.resolve(platforms[0].configXMLPath, '..') : platforms[0].platformPath,
                    platforms: platforms
                };

                deferred.resolve(retObj);
            } else {
                log.silly(moduleName, 'No platforms were able to be detected');
                var noProjectDetectedErr = errors.getError('NOPLATFORMSDETECTED');
                deferred.reject(noProjectDetectedErr);
            }
        });
    } else {
        log.silly(moduleName, 'No extensions were found with type "mdo.platforms"');
        var noExtensionsFoundErr = errors.getError('NOEXTENSIONSFOUND', 'mdo.platforms');
        deferred.reject(noExtensionsFoundErr);
    }
    return deferred.promise;
};

function processPossibleMultipleProjects(platforms) {
  var cordovaPlatforms = [];
  var nativePlatforms = [];
  var matchCurrentDir;
  var index = -1;
  var newIndex = -1;
  var cwd = process.cwd();

  platforms.forEach(function (platform) {
    if(platform.platformId.indexOf('native') >= 0) {
      if((newIndex = cwd.indexOf(path.basename(platform.platformPath))) >= 0) {
        if(newIndex > index) {
          matchCurrentDir = [platform];
          index = newIndex;
        } else if (newIndex === index) {
          matchCurrentDir.push(platform);
        }
      }
      nativePlatforms.push(platform);
    } else {
      cordovaPlatforms.push(platform);
    }
  });

  if(nativePlatforms.length > 1 || (cordovaPlatforms.length > 1 && nativePlatforms >= 1)) {
    if(matchCurrentDir) {
      return matchCurrentDir;
    } else if( cordovaPlatforms.length > 0){
      if(cwd.indexOf(path.resolve(cordovaPlatforms[0].configXMLPath, '..')) >= 0) {
        return cordovaPlatforms;
      }
    } else {
      return platforms;
    }
  } else {
    return platforms;
  }
}
