/* © SRSoftware 2025 */
package de.srsoftware.umbrella.legacy;


import static de.srsoftware.tools.Optionals.nullable;
import static de.srsoftware.umbrella.core.ModuleRegistry.*;
import static de.srsoftware.umbrella.core.constants.Field.TOKEN;
import static de.srsoftware.umbrella.core.constants.Field.URI;
import static de.srsoftware.umbrella.core.exceptions.UmbrellaException.invalidField;

import com.sun.net.httpserver.HttpExchange;
import de.srsoftware.configuration.Configuration;
import de.srsoftware.tools.Path;
import de.srsoftware.tools.SessionToken;
import de.srsoftware.tools.Tag;
import de.srsoftware.umbrella.core.BaseHandler;
import de.srsoftware.umbrella.core.model.Token;
import de.srsoftware.umbrella.core.model.UmbrellaUser;
import java.io.IOException;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

public class NotesLegacy extends BaseHandler {

	public NotesLegacy(Configuration config) {
		super();
	}

	@Override
	public boolean doGet(Path path, HttpExchange ex) throws IOException {
		var url = url(ex);
		if (path.empty() || url.endsWith("/view")) return sendRedirect(ex, url.replaceAll("/legacy/","/"));
		return super.doGet(path, ex);
	}

	@Override
	public boolean doPost(Path path, HttpExchange ex) throws IOException {
		var params = formData(ex);

		Optional<Token> token = SessionToken.from(ex).map(Token::of);
		if (token.isEmpty()) token = nullable(params.get(TOKEN)).map(Object::toString).map(Token::of);
		var user = userService().loadUser(token);
		if (user.isEmpty()) return unauthorized(ex);

		return switch (path.pop()){
			case "html" -> postNotesHtml(ex,params);
			default -> super.doPost(path,ex);
		};
	}

	private boolean postNotesHtml(HttpExchange ex, Map<String, Object> params) throws IOException {
		if (!(params.get(URI) instanceof String uri)) throw invalidField(URI,"URI of the form \"module:entry-id\"");
		var parts = uri.split(":",2);
		if (parts.length<2) throw invalidField(URI,"URI of the form \"module:entry-id\"");
		var module = parts[0];
		var entryId = parts[1];
		var notes = noteService().getNotes(module,entryId);
		var authors = new HashMap<Long, UmbrellaUser> ();
		var users = userService();
		for (var note : notes.values()) {
			var userId = note.authorId();
			authors.computeIfAbsent(userId,k -> users.loadUser(userId));
		}
		var html = new Tag("div");
		for (var note : notes.values()){
			var author = authors.get(note.authorId());
			var authorName = author != null ? author.name() : "";
			new Tag("fieldset")
					.add(new Tag("legend").content(authorName))
					.add(new Tag("legend").content(note.timestamp().format(DateTimeFormatter.ISO_DATE_TIME)))
					.add(new Tag("div").content(markdownService().markdown(note.text())))
					.addTo(html);
		}
		return sendContent(ex,html.toString(2));
	}
}
