/*
Espe | Ein schlichtes Werkzeug zur Mitglieder-Verwaltung | Frontend
Copyright (C) 2024 Christian Fraß

This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public 
License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later 
version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied 
warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program. If not, see 
<https://www.gnu.org/licenses/>. 
 */

lib_plankton.zoo_page.register(
	"login",
	(parameters, target_element) => {
		target_element.appendChild(template_request("login"));
		
		target_element.querySelector(".login-title").textContent = lib_plankton.translate.get("page.login.title");

		const form = new lib_plankton.zoo_form.class_form<
			{
				name : string;
				password : string;
			},
			{
				name : string;
				password : string;
			}
		>(
			x => x,
			x => x,
			new lib_plankton.zoo_input.class_input_group(
				[
					{
						"name": "name",
						"input": new lib_plankton.zoo_input.class_input_text(),
						"label": lib_plankton.translate.get("page.login.name"),
					},
					{
						"name": "password",
						"input": new lib_plankton.zoo_input.class_input_password(),
						"label": lib_plankton.translate.get("page.login.password"),
					},
				]
			),
			[
				{
					"label": lib_plankton.translate.get("page.login.submit"),
					"procedure": async (get_value, get_representation) => {
						const value = await get_value();
						(
							_espe.backend.login(value.name, value.password)
							.then(
								() => {
									lib_plankton.zoo_page.set({"name": "member_list", "parameters": {}});
									update_nav({"mode": "logged_in"});
								}
							)
							.catch(
								(error) => {
									form.input_write(
										{
											"name": value.name,
											"password": ""
										}
									);
								}
							)
						);
					},
				}
			]
		);
		form.setup(target_element.querySelector(".login-form") as HTMLElement);
	}
);
