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

var moduleName = 'parsePlatformInfo';

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

    log.verbose(moduleName, 'Parsing platform: ' + platformId);
    var parsingExtensions = findExtensions(global.MDO_MAIN_EXTENSIONS_PATH, 'mdo.platforms');
    if(parsingExtensions) {
        parsingExtensions.forEach(function (extension) {
            if(extension.id === platformId) {
                log.silly(moduleName, 'Parsing for platform: ' + extension.id);
                parsePromise = extension.export.parse(rootDir);
            }
        });

        if(parsePromise) {
            parsePromise.then(function (parsedInfo) {
                d.resolve(parsedInfo);
            }, function (err) {
                d.reject(err);
            });
        } else {
            log.silly(moduleName, 'could not find a parsing method for platform: ' + platformId);
            var noPlatformFoundErr = errors.getError('NOPLATFORMDETECTED', platformId);
            d.reject(noPlatformFoundErr);
        }
    } else {
        log.silly(moduleName, 'no platform extensions are present');
        var noExtensionsFoundErr = errors.getError('NOEXTENSIONSFOUND', 'mdo.platforms');
        d.reject(noExtensionsFoundErr);
    }

    return d.promise;
};
