/*
	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 path = require('path');
var Q = require('q');
//private
var errors = require('mdo-errors');
var findExtensions = require('pluggington');

var moduleName = 'detect-platform';

module.exports = function (platformId) {
    var d = Q.defer(),
        detectPromise;

    log.verbose(moduleName, 'trying to detect platform: ' + platformId);
    var detectPlatformExtensions = findExtensions(global.MDO_MAIN_EXTENSIONS_PATH, 'mdo.platforms');

    if(detectPlatformExtensions) {
        detectPlatformExtensions.forEach(function (extension) {
            if(extension.id === platformId) {
                detectPromise = extension.export.detect();
            }
        });
    }

    if(detectPromise) {
        detectPromise
        .then(function (result) {
            var retObj;
            if(result) {
                retObj = {
                    isCordova: result.configXMLPath !== undefined ? true : false,
                    rootDir: result.configXMLPath !== undefined ? path.resolve(result.configXMLPath, '..') : result.platformPath,
                    platformId: result.platformId
                };
            }

            d.resolve(retObj);
        }, function () {
            log.silly(moduleName, 'No platforms were able to be detected');
            var noPlatformFoundErr = errors.getError('NOPLATFORMDETECTED', platformId);
            d.reject(noPlatformFoundErr);
        });
    } else {
        log.silly(moduleName, 'No extensions were found with type "mdo.platforms"');
        var noExtensionsFoundErr = errors.getError('NOEXTENSIONSFOUND', 'mdo.platforms');
        d.reject(noExtensionsFoundErr);
    }

    return d.promise;
};
