/*
	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 propertiesParser = require('properties-parser');
var url = require('url');
var errors = require('mdo-errors');
var punycode = require('punycode');

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

function getRuntime(editor) {
  var valueInFile = editor.get('wlServerContext');
  return valueInFile && valueInFile.charAt(0) === '/' &&
         valueInFile.slice(-1) === '/' ? valueInFile.slice(1, -1) : 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.set('wlServerProtocol', protocol);
  editor.set('wlServerHost', punycode.toASCII(serverURL.hostname));
  editor.set('wlServerPort', serverURL.port);
}

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

  propertiesParser.createEditor(propertiesPath, function (err, editor) {
    if (err) {
      // Config didn't exist or is invalid
      d.reject(errors.getError('CANNOT_PARSE_FILE', propertiesPath,
                               '.properties'));
    } else {
      d.resolve({
        server: getServer(editor),
        runtime: getRuntime(editor),
        language_preferences: editor.get('languagePreferences'),
      });
    }
  });

  return d.promise;
};

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

  propertiesParser.createEditor(propertiesPath, function (err, editor) {
    if (err) {
      // Config didn't exist or is invalid
      d.reject(errors.getError('CANNOT_PARSE_FILE', propertiesPath,
                               '.properties'));
    } else {
      // Set key and write file
      if (key === 'server') {
        setServer(editor, value);
      } else if (key === 'runtime') {
        editor.set('wlServerContext', '/' + value + '/');
      } else if (key === 'language_preferences') {
        editor.set('languagePreferences', value);
      }
      editor.save(propertiesPath, function(err) {
        if (err) {
          d.reject(errors.getError('ERRWRITEFILE', propertiesPath));
        } else {
          d.resolve();
        }
      });
    }
  });

  return d.promise;
};
