"use strict";

const syncpipe = require("syncpipe");
const table = require("table").table;
const chalk = require("chalk");

const unreachable = require("./unreachable");

function renderTable(data) {
	return table(data, {
		border: {
			topBody: "",
			topJoin: "",
			topLeft: "",
			topRight: "",
			bottomBody: "",
			bottomJoin: "",
			bottomLeft: "",
			bottomRight: "",
			bodyLeft: "",
			bodyRight: "",
			joinLeft: "",
			joinRight: ""
		}
	});
}

module.exports = function renderSchema(dbSchema) {
	return Object.entries(dbSchema)
		.map(([ collectionName, schema ]) => {
			let tableData = [
				[ chalk.bold("Column"), chalk.bold("Type"), " " ]
			].concat(syncpipe(schema.fields, [
				(_) => Object.entries(_),
				(_) => _.filter(([ _columnName, definition ]) => definition != null),
				(_) => _.map(([ fieldName, definition ]) => {
					let link = definition.linkTo;

					if (link != null) {
						if (link.type === "remoteField") {
							let linkedField = dbSchema[link.collectionName].fields[link.fieldName];

							return [ fieldName, chalk.gray(linkedField.type), `-> ${link.collectionName}.${link.fieldName}` ];
						} else {
							unreachable("Non-remoteField link encountered");
						}
					} else {
						return [ fieldName, definition.type, " " ]; // FIXME: Linked type
					}
				})
			]));
			
			return chalk.bold.green(collectionName) + "\n\n" + renderTable(tableData);
		})
		.join("\n\n");
};
