/*
	Licensed Material - Property of IBM

	(C) Copyright 2015,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 log = require('npmlog');
var path = require('path');
var Q = require('q');
var buildClientProperties = require('./buildClientProperties');
var readClientProperties = require('./readClientProperties');

var moduleName = 'processClientProperties';

function processClientProperties(platformObj, serverInfo, runtime) {
	var d = Q.defer();
	var mfpClientPath = path.resolve(platformObj.windowsEnvPath, 'strings');
	var templateFilePath = path.resolve(__dirname, 'resources');
	var editorData;

	try {
		fs.statSync(mfpClientPath);
	} catch(err) {
		log.verbose(moduleName, 'strings folder did not exist, creating it now');
		fs.mkdirSync(mfpClientPath);
	}

	readClientProperties(mfpClientPath, 'mfpclient.resw')
	.then(function (reswObj) {		//Success call, has contents of wlclient.properties
		return reswObj;
	}, function () {		//Error: wlclient.properties does not exist so create one
		return readClientProperties(templateFilePath, 'mfpclient-template.resw');
	})
	.then(function (reswObj) {
		editorData = buildClientProperties(reswObj, serverInfo, runtime);
		editorData.writeFile(path.resolve(mfpClientPath, 'mfpclient.resw'));
		d.resolve();
	})
	.catch(function (err) {
		d.reject(err);
	});

	return d.promise;
}

module.exports = processClientProperties;
