
namespace _zeitbild.repository.user
{
	
	/**
	 */
	var _store : (
		null
		|
		lib_plankton.storage.type_store<
			_zeitbild.type.user_id,
			Record<string, any>,
			{},
			lib_plankton.storage.type_sql_table_autokey_search_term,
			Record<string, any>
		>
	) = null;
	
	
	/**
	 */
	function get_store(
	) : lib_plankton.storage.type_store<
		_zeitbild.type.user_id,
		Record<string, any>,
		{},
		lib_plankton.storage.type_sql_table_autokey_search_term,
		Record<string, any>
	>
	{
		if (_store === null) {
			_store = lib_plankton.storage.sql_table_autokey_store(
				{
					"database_implementation": _zeitbild.database.get_implementation(),
					"table_name": "users",
					"key_name": "id",
				}
			);
		}
		else {
			// do nothing
		}	
		return _store;
	}
	
	
	/**
	 */
	function encode(
		user_object : _zeitbild.type.user_object
	) : Record<string, any>
	{
		return {
			"name": user_object.name,
			"email_address": user_object.email_address,
		};
	}
	
	
	/**
	 */
	function decode(
		row : Record<string, any>
	) : _zeitbild.type.user_object
	{
		return {
			"name": row["name"],
			"email_address": row["email_address"],
		};
	}
	
	
	/**
	 */
	export async function read(
		user_id : _zeitbild.type.user_id
	) : Promise<_zeitbild.type.user_object>
	{
		const row : Record<string, any> = await get_store().read(user_id);
		const user_object : _zeitbild.type.user_object = decode(row);
		return Promise.resolve<_zeitbild.type.user_object>(user_object);
	}
	
	
	/**
	 */
	export async function create(
		user_object : _zeitbild.type.user_object
	) : Promise<_zeitbild.type.user_id>
	{
		const row : Record<string, any> = encode(user_object);
		const user_id : _zeitbild.type.user_id = await get_store().create(row);
		return Promise.resolve<_zeitbild.type.user_id>(user_id);
	}
	
	
	/**
	 */
	export async function identify(
		name : string
	) : Promise<_zeitbild.type.user_id>
	{
		const hits : Array<{key : _zeitbild.type.user_id; preview : any;}> = await get_store().search(
			{
				"expression": "(name = $name)",
				"arguments": {
					"name": name,
				}
			}
		);
		if (hits.length <= 0) {
			return Promise.reject<_zeitbild.type.user_id>(new Error("not found"));
		}
		else {
			return Promise.resolve<_zeitbild.type.user_id>(hits[0].key);
		}
	}
	
}
