"use strict";

const Promise = require("bluebird");
const createEventEmitter = require("create-event-emitter");
const defaultValue = require("default-value");

const mergeMetadata = require("./util/merge-metadata");

module.exports = function createFileSink(options) {
	let emitter = createEventEmitter({
		__buildStep: "sink",
		displayName: options.displayName,
		supportsAcknowledgment: options.supportsAcknowledgment,
		supportsStreams: options.supportsStreams,
		sink: function (inputFile) {
			let {metadata} = inputFile;

			try {
				let result = options.sink(inputFile);

				if (result != null) {
					return Promise.try(() => {
						return result;
					}).then((extraMetadata = {}) => {
						emitter.emit("sunk", {
							metadata: mergeMetadata(extraMetadata, {
								inputFileMetadata: metadata
							}),
							stream: inputFile.stream,
							contents: inputFile.contents
						});
					}).catch((err) => {
						reportError(inputFile, err);
					});
				}
			} catch (err) {
				reportError(inputFile, err);
			}
		}
	});

	function reportError(inputFile, error) {
		emitter.emit("error", {
			file: inputFile,
			error: error,
			isFatal: error.isFatal,
			step: emitter
		});
	}

	return emitter;
};
