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

//private
var errors = require('mdo-errors');
//public
var fs = require('fs');
var log = require('npmlog');
var p = require('path');
var Q = require('q');

/*
 * contents is the object that you want to write to the file
 * name is the fully qualified name of the file, i.e native_ios-iOSnative-1.0.wlapp
 * path is the path where the file will be placed
 */
function createFile(contents, name, path) {
    var d = Q.defer();

    var filename = name;
    var filepath;
    //if no path is set use cwd
    if(path === undefined) {
        filepath = p.resolve(process.cwd(), '.');
    } else {
        filepath = path;
    }

    var file = p.join(filepath, filename);
    fs.writeFile(file, contents, {encoding: 'utf-8'}, function(err) {
        if(err) {
            log.verbose('createFile', 'fs.writeFile error: '+err+' '+JSON.stringify(err));
            var cannotWriteFileError = errors.getError('ERRWRITEFILE', file);
            d.reject(cannotWriteFileError);
        }
        else {
            d.resolve();
        }
    });

    return d.promise;
}

module.exports = createFile;
