
namespace _zeitbild.database
{
	
	/**
	 */
	const _compatible_revisions : Array<string> = [
		"r1",
	];
	
		
	/**
	 */
	export function get_implementation(
	) : lib_plankton.database.type_database
	{
		switch (_zeitbild.conf.get().database.kind) {
			case "sqlite": {
				type type_parameters = {
					path : string;
				};
				const parameters : type_parameters = (_zeitbild.conf.get().database.data as type_parameters);
				return lib_plankton.database.sqlite_database(
					{
						"path": parameters.path,
					}
				);
				break;
			}
			case "postgresql": {
				type type_parameters = {
					host : string;
					port ?: int;
					username : string;
					password : string;
					schema : string;
				};
				const parameters : type_parameters = (_zeitbild.conf.get().database.data as type_parameters);
				return lib_plankton.database.postgresql_database(
					{
						"host": parameters.host,
						"port": parameters.port,
						"username": parameters.username,
						"password": parameters.password,
						"schema": parameters.schema,
					}
				);
			}
			default: {
				throw (new Error("database implementation not available: " + _zeitbild.conf.get().database.kind));
			}
		}
	}
	
	
	/**
	 */
	function get_revision(
	) : Promise<(null | string)>
	{
		return (
			get_implementation().query_select(
				{
					"source": "_meta",
					"fields": ["revision"],
				}
			)
			.then<(null | string)>(
				(rows) => Promise.resolve<(null | string)>(rows[0]["revision"])
			)
			.catch<(null | string)>(
				(reason) => {
					lib_plankton.log.warning(
						"database_get_revision_error",
						{
							"reason": String(reason),
						}
					);
					return Promise.resolve<(null | string)>(null);
				}
			)
		);
	}
	
	
	/**
	 */
	export async function check(
	) : Promise<void>
	{
		const revision : (null | string) = await get_revision();
		lib_plankton.log.info(
			"database_check",
			{
				"revision_found": revision,
				"revisions_compatible": _compatible_revisions,
			}
		);
		if (revision === null) {
			return Promise.reject<void>(new Error("database appearently missing"));
		}
		else {
			if (! _compatible_revisions.includes(revision)) {
				return Promise.reject<void>(new Error("database revision incompatible; found: " + revision + "; required: " + String(_compatible_revisions)));
			}
			else {
				return Promise.resolve<void>(undefined);
			}
		}
	}
	
}
