/*
	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';

//public
var fs = require('fs');
var log = require('npmlog');
var path = require('path');
var Q = require('q');
//private
var readClientProperties = require('./readClientProperties');
var buildClientProperties = require('./buildClientProperties');
var createFile = require('./createFile');

var moduleName = 'processPropertiesFile';

module.exports = function processPropertiesFile(platformObj, serverInfo, runtime) {
	var d = Q.defer();

	var mfpclientFileName = "mfpclient.properties";
	var mfpClientPath = path.resolve(platformObj.platformPath, 'app', 'src', 'main', 'assets');
	var shouldReadFile = true;
	var editorData;

	try {
		fs.statSync(mfpClientPath);
	} catch(err) {
		log.verbose(moduleName, 'app/src/main/assets did not exist, creating it now');
		fs.mkdirSync(mfpClientPath);
	}

	if(shouldReadFile) {
		readClientProperties(mfpClientPath)
		.then(function (editor) {		//Success call, has contents of wlclient.properties
			editorData = buildClientProperties(serverInfo, runtime, editor);
			createFile(editorData, mfpclientFileName, mfpClientPath)
			.then(function () {
				d.resolve();
			}, function (err) {
				d.reject(err);
			});
		}, function () {		//Error: wlclient.properties does not exist so create one
			editorData = buildClientProperties(serverInfo, runtime);
			createFile(editorData, mfpclientFileName, mfpClientPath)
			.then(function () {
				d.resolve();
			}, function (err) {
				d.reject(err);
			});
		});
	}

	return d.promise;
};
