/*
	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 moduleName = 'delegateBuildingPropertiesFile'; // - name for clarification during logging

var log = require('npmlog');
var Q = require('q');
//private modules
var findExtensions = require('pluggington');

//This function uses pluggington to check all of the mdo.platforms extensions and use there exported processPropertiesFile method
module.exports = function(platforms, server, runtime) {
    var detectPlatformExtensions = findExtensions(global.MDO_MAIN_EXTENSIONS_PATH, 'mdo.platforms');
    var buildFilePromise = Q.defer();
    var d = Q.defer();

    //We have the platforms array, we peel off [0] to call the processPropertiesFile, if Cordova it will pass the platforms in to build each one accordingly.  If it a standalone native project it will just have the [0] object.
    var platformId = platforms[0].platformId;
    var processFileFunc;
    

    if (detectPlatformExtensions) {
        detectPlatformExtensions.forEach(function(extension) {
          if(extension.id === platformId) {
            processFileFunc = extension.export.processPropertiesFile;
          }
        });
    }
    //If the project is Cordova then it doesn't matter what platform object we use since all Cordova platforms share the processPropertiesFile function
    //If we are not cordova we run the projects processPropertiesFile function
    if (processFileFunc) {
        //If we are a Cordova project send in platforms array, else send in [0] platform
        if (platformId.indexOf('cordova') >= 0) {
            buildFilePromise = processFileFunc(platforms[0].configXMLPath, server.fullURL, runtime);
        } else {
            
            if(platformId !== 'native-browser') buildFilePromise = processFileFunc(platforms[0], server, runtime);

        }
    }

    if (!buildFilePromise) {
        //we couldn't find the platform to built the properties file of
        log.silly(moduleName, 'could not find platform to build property file for');
        d.reject();
    }else if(platformId === 'native-browser'){
                  d.resolve();
    } else {

        buildFilePromise.then(function() {
            log.silly(moduleName, 'Property file successfully built');
            d.resolve();
        }, function(err) {
            //report error building filename
            log.silly(moduleName, 'Error building property file for: ' + platformId);
            d.reject(err);
        });
    }
    return d.promise;
};