/*
	Licensed Material - Property of IBM

	(C) Copyright 2015 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 p = require('path');
var Q = require('q');
var log = require('npmlog');
var VError = require('verror');

/*
 * editorData is the editor object to write to the file
 * name is the fully qualified name of the file, i.e native_android-Androidnative-1.0.wlapp
 * path is the path where the file will be placed
 */
function createFile(editorData, 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);
    editorData.save(file, function(err) {
        if(err) {
            log.verbose('createFile', 'save error: '+err+' '+JSON.stringify(err));
            var cannotWriteFileError = errors.getError('ERRWRITEFILE', file);
            var newErr = new VError(cannotWriteFileError, err);
            d.reject(newErr);
        }
        else {
            d.resolve();
        }
    });

    return d.promise;
}

module.exports = createFile;
