"use strict";

const createEventEmitter = require("create-event-emitter");
const path = require("path");

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

module.exports = function createFileSource(options) {
	function resolvePath(relativePath) {
		return path.resolve("", relativePath);
	}

	let emitter = createEventEmitter({
		__buildStep: "source",
		displayName: options.displayName,
		supportsTeardown: options.supportsTeardown,
		basePath: options.basePath,
		initialize: function (initializationOptions) {
			try {
				return options.initialize({
					options: initializationOptions,
					resolvePath: resolvePath,
					pushFile: newFile,
					reportError: reportError
				});
			} catch (error) {
				reportError(error);
			}
		},
		teardown: options.teardown
	});

	function newFile({metadata, contents, stream}) {
		let augmentedMetadata = mergeMetadata(metadata, {
			transform: emitter,
			sourcedDate: new Date()
		});

		emitter.emit("file", {
			metadata: augmentedMetadata,
			contents: contents,
			stream: stream
		});
	}

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

	return emitter;
};
