"use strict";

const Promise = require("bluebird");
const fs = Promise.promisifyAll(require("fs"));
const mkdirpAsync = Promise.promisify(require("mkdirp"));
const path = require("path");

const createFileSink = require("./file-sink");

module.exports = function (targetPath) {
	return createFileSink({
		displayName: `Save to directory (${targetPath})`,
		supportsAcknowledgment: true,
		/* FIXME: Implement stream support */
		supportsStreams: false,
		sink: function ({metadata, contents}) {
			return Promise.try(() => {
				/* FIXME: Verify that all writes are within the targetPath */
				let targetFilePath = path.join(targetPath, metadata.relativePath);

				return Promise.try(() => {
					return mkdirpAsync(path.dirname(targetFilePath));
				}).then(() => {
					return fs.writeFileAsync(targetFilePath, contents);
				}).then(() => {
					return {
						targetPath: targetFilePath
					};
				});
			});
		}
	});
};
