"use strict";

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

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

/* FIXME: Associate output files with input files! */

module.exports = function createSingleFileTransform(options) {
	let emitter = createEventEmitter({
		__buildStep: "transform",
		displayName: options.displayName,
		supportsStreams: options.supportsStreams,
		supportsVirtualFiles: options.supportsVirtualFiles,
		supportsVirtualFilesystem: options.supportsVirtualFilesystem,
		transform: function (input) {
			let startTime = Date.now();

			return Promise.try(() => {
				return options.transform({
					metadata: input.metadata,
					contents: input.contents,
					stream: input.stream
				});
			}).then(({metadata, contents, stream}) => {
				emitter.emit("file", {
					metadata: mergeMetadata(metadata, {
						inputFileMetadata: input.metadata,
						lastModified: defaultValue(metadata.lastModified, new Date()),
						step: this,
						stepDuration: Date.now() - startTime
					}),
					contents: contents,
					stream: stream
				});
			}).catch((error) => {
				emitter.emit("error", {
					file: input,
					step: this,
					error: error,
					isFatal: error.isFatal,
					duration: Date.now() - startTime
				});
			});
		}
	});

	return emitter;
};
