/*
	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 Q = require('q');
var fs = require('fs');
var et = require('elementtree');
var subElement = require('elementtree').SubElement;
var url = require('url');
var errors = require('mdo-errors');
var punycode = require('punycode');

/**
 * Helper method to parse the key/value pairs out of the elementTree for the
 * mfpclient.plist
 * @param etree - etree of the parsed plist data
 * @returns Object - containing the key value pairs
 */
function parsePlist(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;
}

function readAndParseClientPropertiesFile(propertiesPath) {
  var d = Q.defer();
  fs.readFile(propertiesPath, function (err, data) {
    var tree;
    if (err) {
      d.reject(errors.getError('FILENOEXISTS', propertiesPath));
    } else {
      try {
        tree = et.parse(data.toString());
        d.resolve(tree);
      } catch (err) {
        d.reject(errors.getError('CANNOT_PARSE_FILE', propertiesPath,
                                 '.xml'));
      }
    }
  });
  return d.promise;
}

function setPlistKey(tree, key, value) {
  var children = tree.find('dict')._children;

  // Find the key element, change the value of the child following
  for (var i = 0; i < children.length; i += 2) {
    if (children[i].text === key && children[i].tag === 'key') {
      children[i+1].tag = 'string';
      children[i+1].text = value;
      return;
    }
  }

  // Key not found, add key and value to plist
  var keyElement = subElement(tree.find('dict'), 'key');
  keyElement.text = key;
  var valueElement = subElement(tree.find('dict'), 'string');
  valueElement.text = value;

  return tree;
}

function getServer(plistKeyToValue) {
  if (plistKeyToValue.protocol && plistKeyToValue.host &&
      plistKeyToValue.port) {
    return plistKeyToValue.protocol + '://' + plistKeyToValue.host +
           ':' + plistKeyToValue.port;
  }
  return undefined;
}

function getRuntime(plistKeyToValue) {
  // Client files expect runtime to start and end with /.
  // i.e. If the user tries to set runtime to 'mfp', the value that gets written
  // is /mfp/
  var valueInFile = plistKeyToValue.wlServerContext;
  return valueInFile.charAt(0) === '/' && valueInFile.slice(-1) === '/' ?
         valueInFile.slice(1, -1) : undefined;
}

function setServer(tree, value) {
  var serverURL = url.parse(value);
  // serverURL.protocol includes trailing ':', for example 'http:'
  var protocol = serverURL.protocol.substring(0, serverURL.protocol.length - 1);
  setPlistKey(tree, 'protocol', protocol);
  setPlistKey(tree, 'host', punycode.toASCII(serverURL.hostname));
  setPlistKey(tree, 'port', serverURL.port);
}

module.exports.getAppConfigKeys = function(propertiesPath) {
  var d = Q.defer();
  readAndParseClientPropertiesFile(propertiesPath).then(function(tree) {
    var plistKeyToValue = parsePlist(tree);
    d.resolve({
      server: getServer(plistKeyToValue),
      runtime: getRuntime(plistKeyToValue),
      language_preferences: plistKeyToValue.languagePreferences
    });
  })
  .fail(d.reject);

  return d.promise;
};

module.exports.setAppConfigKey = function(propertiesPath, key, value) {
  var d = Q.defer();

  readAndParseClientPropertiesFile(propertiesPath)
  .then(function(tree) {
    if (key === 'server') {
      setServer(tree, value);
    } else if (key === 'runtime') {
      setPlistKey(tree, 'wlServerContext', '/' + value + '/');
    } else if (key === 'language_preferences') {
      setPlistKey(tree, 'languagePreferences', value);
    }
    fs.writeFile(propertiesPath, tree.write({indent: 2}), function(err) {
      if (err) {
        d.reject(errors.getError('ERRWRITEFILE', propertiesPath));
      } else {
        d.resolve();
      }
    });
  })
  .fail(d.reject);

  return d.promise;
};

