/*
	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 buildClientPlist = require('./buildClientPlist');
var readClientPlist = require('./readClientPlist');
var createFile = require('./createFile');
var glob = require('glob');
var path = require('path');
var Q = require('q');

function processClientPlist(platformObj, appInfo, serverInfo, runtime) {
  var d = Q.defer();

  var plistFileName = "mfpclient.plist",
       clientPlistData,
      clientFilePath,
      clientFile;

  clientFile = glob.sync('**/' + plistFileName, {cwd: platformObj.platformPath});
  if(clientFile && clientFile.length > 0) {
    //Chop off the filename and just grab the dir
    clientFilePath = path.join(platformObj.platformPath, clientFile[0], '..');
  } else {
    clientFilePath = platformObj.platformPath;
  }

  readClientPlist(clientFilePath)
  .then(function (plistData) {    //Success call, has contents of worklight.plist
    var clientPlistData = buildClientPlist(appInfo, serverInfo, runtime, plistData);
    createFile(clientPlistData, plistFileName, clientFilePath)
    .then(function () {
      d.resolve();
    }, function (err) {
      d.reject(err);
    });
  }, function () {    //Error: worklight.plist does not exist so create one
    clientPlistData = buildClientPlist(appInfo, serverInfo, runtime);
    createFile(clientPlistData, plistFileName, clientFilePath)
    .then(function () {
      d.resolve();
    }, function (err) {
      d.reject(err);
    });
  });

  return d.promise;
}

module.exports = processClientPlist;
