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

/**
 * Helper method to parse the key/value pairs out of the elementTree for the worklight.plist
 * @param etree - etree of the parsed plist data
 * @returns Object - containing the key value pairs
 */
function parseObjectValues(etree) {
    var plistObj = {};
    var etreeValues = etree._root._children[0]._children;
    for(var i = 0; i < etreeValues.length; i = i+2) {
        plistObj[etreeValues[i].text] = etreeValues[i+1].text;
    }

    return plistObj;
}

/**
 * @param file - glob file which contains the path to worklight.plist file
*/
function readClientPlist(cwd){
    var d = q.defer();
    var plistTree;

    fs.readFile(path.join(cwd, 'mfpclient.plist'),{encoding:'utf8'}, function (err, xmlString) {
            if(err) {
                log.verbose('readClientProperties', 'Failed to read mfpclient.plist: '+err+' '+JSON.stringify(err));
                d.reject();
            } else {
                try {
                    xmlString = xmlString.replace('\ufeff', '');
                    plistTree = et.parse(xmlString);
                    var plistObj = parseObjectValues(plistTree);
                    d.resolve(plistObj);
                } catch (err) {
                    log.verbose('readClientProperties', 'Failed to parse mfpclient.plist: '+err+' '+JSON.stringify(err));
                    d.reject();
                }

            }
    });
    return d.promise;

}

module.exports = readClientPlist;
