#!/usr/bin/env node

"use strict";

const Promise = require("bluebird");
const yargs = require("yargs");
const matchValue = require("match-value");
const chalk = require("chalk");

const loadConfiguration = require("../src/load-configuration");
const generateSchema = require("../src/schema-generator");
const renderSchema = require("../src/render-schema");
const processSchemaUpdate = require("../src/process-schema-update");

// FIXME: Update to take timestamps instead of revision numbers (and autocomplete them!)
let argv = yargs
	.command("change <description>", "Create a new schema revision", {
		description: { describe: "A brief textual description of the purpose of the revision" }
	})
	.command("upgrade <revision>", "Upgrade the database to a new schema revision", {
		revision: { describe: "The number of the revision to upgrade to (or 'latest')" }
	})
	.command("undo", "Undo the most recent schema revision upgrade")
	.command("show <revision>", "Show the full database schema at a given revision", {
		revision: { describe: "The number of the revision at which the schema should be shown (or 'latest')" }
	})
	.argv;

// FIXME: Error/help when no subcommand has been specified

// console.log(argv);

return Promise.try(() => {
	return loadConfiguration();
}).then(({ configuration, configurationPath }) => {
	let state = { configurationPath, configuration };

	// FIXME: Make configurable
	const schemaProvider = require("../src/schema-providers/fs")(state);

	matchValue(argv._[0], {
		change: () => {
			return Promise.try(() => {
				return schemaProvider.create({ description: argv.description });
			}).then(({ statusMessage }) => {
				console.log(chalk.green(`✔ ${statusMessage}`));
			});
		},
		upgrade: () => {
			return Promise.try(() => {
				return schemaProvider.getAll();
			}).then((schemaUpdates) => {
				let processed = schemaUpdates.map((update) => {
					return processSchemaUpdate(update);
				});
				
				// console.log(require("util").inspect(processed, { colors: true, depth: null }));
			});

			// TODO: Allow-gap option to permit filling in 'gapped migrations' (eg. after an earlier migration gets merged in via branch merge)
		},
		undo: () => {
			console.log("undo");
		},
		show: () => {
			return Promise.try(() => {
				return schemaProvider.getAll();
			}).then((schemaUpdates) => {
				let schema = generateSchema(schemaUpdates);
				console.log(renderSchema(schema));
			});
		}
	});
});
