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

function getTextForPlistKey(elementTree, keyValue) {
    var children = elementTree._root._children[0]._children;
    var text;
    for(var i = 0; i < children.length; i++) {
        if(keyValue === children[i].text) {
            text =  children[i+1].text;
            break;
        }
    }

    return text;
}
/**
    Tries to find metadata out of existing Native Client Project
    @param rootDir: the root directory of where the Info.plist exists
    @returns metadata
    {
        'app.ios.bundle.id': 'com.ibm.BlueList', (only for ios)
        'app.version': '1.0.0',
        'app.displayname': 'BlueList',
        'app.id': 'com_ibm_BlueList',
        'app.packagename': 'com.ibm.bluelist' (only for android)
    }
*/
module.exports = function (rootDir){
    var d = q.defer();

    var clientMetadata = {};
    var clientInfoFilePath;
    var xmlString;

    clientMetadata['app.dotId'] = "";
    clientMetadata['app.version'] = "";
    clientMetadata['app.name'] = "";

    try{
        //then path points to the root of XCode Projects
        //So older Xcode projects had two Info.plist files, one in MyProjectTest and MyProject.  The one in MyProjectTest does not have the shortBundleVersionString.  So peel off the appName and then make sure we get the correct Info.plist
        var appName = rootDir.split(path.sep);
        appName = appName[appName.length - 1];
        var InfoPlistPath = path.resolve(rootDir, appName);
        clientInfoFilePath = glob.sync('*Info.plist', {cwd: InfoPlistPath});
            //take the first file
        if(clientInfoFilePath.length !== 0) {
            //Glob found it, append the path it found onto rootDir
            InfoPlistPath = path.resolve(InfoPlistPath, clientInfoFilePath[0]);
            xmlString = fs.readFileSync(InfoPlistPath, {encoding:'utf8'});
            xmlString = xmlString.replace('\ufeff', '');
            var plistTree = et.parse(xmlString);

            var bundleIdentifier = getTextForPlistKey(plistTree, 'CFBundleIdentifier');
            clientMetadata['app.dotId'] = bundleIdentifier.indexOf("$") >= 0 ? "" : bundleIdentifier;

            var version = getTextForPlistKey(plistTree, 'CFBundleShortVersionString');
            clientMetadata['app.version'] = version ? version : '';

            var displayName = getTextForPlistKey(plistTree, 'CFBundleName');
            clientMetadata['app.name'] = displayName.indexOf("$") >= 0 ? "" : displayName;

            d.resolve(clientMetadata);
        } else {
            throw new Error('*-Info.plist file does not exist');
        }
    } catch(err) {
        log.silly('Error parsing *-Info.plist.' + err.message);
        d.reject();
    }

    return d.promise;
};
