/*
	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 reswAPI = require('./process-properties-file/resw-api');
var url = require('url');
var errors = require('mdo-errors');
var punycode = require('punycode');

function getServer(editor) {
  var protocol = editor.getDataEntry('wlServerProtocol');
  var host = editor.getDataEntry('wlServerHost');
  var port = editor.getDataEntry('wlServerPort');
  return protocol && host && port ? protocol + '://' + host + ':' + port :
                                    undefined;
}

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

function getRuntime(editor) {
  var valueInFile = editor.getDataEntry('wlServerContext');
  return valueInFile && valueInFile.charAt(0) === '/' &&
         valueInFile.slice(-1) === '/' ?  valueInFile.slice(1, -1) : undefined;
}

module.exports.getAppConfigKeys = function(propertiesPath) {
  var d = Q.defer();

  (new reswAPI(propertiesPath)).then(function(editor) {
    d.resolve({
      server: getServer(editor),
      runtime: getRuntime(editor),
      language_preferences: editor.getDataEntry('languagePreferences')
    });
  }, function() {
    // Config didn't exist or is invalid
    d.reject(errors.getError('CANNOT_PARSE_FILE', propertiesPath,
                             '.properties'));
  });

  return d.promise;
};

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

  (new reswAPI(propertiesPath)).then(function(editor) {
    if (key === 'server') {
      setServer(editor, value);
    } else if (key === 'runtime') {
      editor.setDataEntry('wlServerContext', '/' + value + '/');
    } else if (key === 'language_preferences') {
      editor.setDataEntry('languagePreferences', value);
    }

    try {
      editor.writeFile();
      d.resolve();
    } catch(err) {
      d.reject(errors.getError('ERRWRITEFILE', propertiesPath));
    }
  }, function() {
    // Config didn't exist or is invalid
    d.reject(errors.getError('CANNOT_PARSE_FILE', propertiesPath,
                             '.properties'));
  });

  return d.promise;
};

