/*
	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 fs = require('fs');
var glob = require('glob');
var log = require('npmlog');
var path = require('path');
var xml2js = require('xml2js');
var q = require('q');

/**
    Tries to find metadata out of existing config.xml for pureCordova projects
*/
module.exports = function (configXMLDir){
    var d = q.defer();

    var clientMetadata = {};
    var xmlString;

    clientMetadata['app.version'] = "";
    clientMetadata['app.name'] = "";
    clientMetadata['app.description'] = "";
    clientMetadata['app.dotId'] = "";
    clientMetadata['app.iosId'] = "";
    clientMetadata['app.androidId'] = "";
    clientMetadata['author.name'] = "";
    clientMetadata['author.email'] = "";
    clientMetadata['author.href'] = "";

    //then path points to the root of XCode Projects
        //take the first file
    try {
        var configXMLPath = glob.sync('config.xml', {cwd: configXMLDir});
        if(configXMLPath.length > 0) {
            configXMLPath = path.resolve(configXMLDir, configXMLPath[0]);
            xmlString = fs.readFileSync(configXMLPath, {encoding:'utf8'});
            xmlString = xmlString.replace('\ufeff', '');
            var parser = new xml2js.Parser({explicitArray:false});
            parser.parseString(xmlString, function (err, result) {
                if(err) {
                    d.reject();
                } else {
                    var configXmlInfo = result.widget;
                    clientMetadata['app.version'] = configXmlInfo.$.version;
                    clientMetadata['app.name'] = configXmlInfo.name;
                    clientMetadata['app.description'] = configXmlInfo.description.trim();
                    clientMetadata['app.dotId'] = configXmlInfo.$.id;
                    clientMetadata['app.iosId'] = configXmlInfo.$['ios-CFBundleIdentifier'];
                    clientMetadata['app.androidId'] = configXmlInfo.$['android-packageName'];
                    clientMetadata['author.name'] = configXmlInfo.author._.trim();
                    clientMetadata['author.email'] = configXmlInfo.author.$.email;
                    clientMetadata['author.href'] = configXmlInfo.author.$.href;
                    clientMetadata['app.mainfile'] = configXmlInfo.content.$.src;
                    d.resolve(clientMetadata);
                }
            });
        } else {
            log.silly('no config.xml file found');
            d.reject();
        }
    } catch (err) {
        log.silly('file being parsed: ' + configXMLPath + ' does not exist');
        d.reject();
    }

    return d.promise;
};
