/*
	Licensed Material - Property of IBM

	(C) Copyright 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 fs = require('fs');
var Q = require('q');
var xml2js = require('xml2js');

module.exports = function reswAPI(reswFilePath) {
  var d = Q.defer(),
      that = this;

  try {
    var parser = new xml2js.Parser();
    fs.statSync(reswFilePath);
    that.reswPath = reswFilePath;
    var reswFile = fs.readFileSync(reswFilePath, {encoding:'utf8'}).replace('\ufeff', '');
    parser.parseString(reswFile, function (err, result) {
      if(err) {
        d.reject(err);
      } else {
        that.reswObj = result;
        d.resolve(that);
      }
    });

    this.setDataEntry = function(dataKey, value) {
      var valueSet = false;

      this.reswObj.root.data.forEach(function (obj) {
        if(obj.$.name === dataKey) {
          obj.value = value;
          valueSet = true;
        }
      });

      return valueSet;
    };

    this.getDataEntry = function(dataKey) {
      var value;

      this.reswObj.root.data.forEach(function (obj) {
        if(obj.$.name === dataKey) {
          //When xml2js reads it in 'value' is in an Array, then if we set it it is not in an Array.  So this covers if you set it and then try to get it
          if(obj.value instanceof Array) {
            value = obj.value[0];
          } else {
            value = obj.value;
          }
        }
      });

      return value;
    };

    this.writeFile = function(filePath) {
      var builder = new xml2js.Builder();
      var xml = builder.buildObject(this.reswObj);
      if(filePath) {
        fs.writeFileSync(filePath, xml);
      } else {
        fs.writeFileSync(this.reswPath, xml);
      }
    };

  } catch(err) {
    d.reject(err);
  }

  return d.promise;
};
