const Path = require('path');
const cfg = require('../config');

function translatePath (file) {
	const root = Path.resolve(cfg.DOUGAL_ROOT);
	const importPaths = cfg.global?.imports?.paths;

	function validate (physicalPath, prefix) {
		if (physicalPath.startsWith(prefix)) {
			return physicalPath;
		} else {
			// An attempt to break out of the logical path?
			console.warn("Attempting to break out of the logical path?", physicalPath, prefix);
			throw {
				status: 404,
				message: "Not found"
			};
		}
	}

	if (Path.isAbsolute(file)) {
		if (typeof importPaths === "string") {
			// Substitute the root for the real physical path
			// NOTE: `root` deals with import_paths not being absolute
			const prefix = Path.resolve(root, importPaths);
			const suffix = Path.resolve(file).replace(/^\/+/, "");
			const physicalPath = Path.resolve(Path.join(prefix, suffix));
			return validate(physicalPath, prefix);
		} else if (typeof importPaths === "object") {
			const parts = Path.resolve(file).split("/").slice(1);
			if (parts[0] in importPaths) {
				const prefix = Path.join("/", importPaths[parts[0]])
				const suffix = parts.slice(1).join("/");
				const physicalPath = Path.resolve(Path.join(prefix, suffix));
				return validate(physicalPath, prefix);
			} else {
				return validate(file, null); // Throws 404
			}
		} else {
			// Most likely importPaths is undefined
			return validate(file, null); // Throws 404
		}
	} else {
		// A relative filepath is always resolved relative to the logical root
		return translatePath(Path.resolve(Path.join("/", file)));
	}

}

function untranslatePath (file) {

}

function logicalRoot () {
	const root = Path.resolve(cfg.DOUGAL_ROOT);
	const importPaths = cfg.global?.imports?.paths;

	if (typeof importPaths === "string") {
		return [ "/" ];
	} else if (typeof importPaths === "object") {
		return Object.keys(importPaths);
	} else {
		// Most likely importPaths is undefined
		return [];
	}
}

module.exports = {
	translatePath,
	untranslatePath,
	logicalRoot
};
