package guestbook;

import io.javalin.Javalin;
import io.javalin.http.Context;

import java.util.ArrayList;
import java.util.List;

/**
 * 2005-style guestbook server.
 *
 * The server doesn't render HTML. It serves a static page (index.html + app.js)
 * and exposes a small JSON API; the browser does the rendering.
 */
public class Server {

    private final List<Message> messages = new ArrayList<>();

    public static void main(String[] args) {
        Server s = new Server();
        Javalin.create(config -> {
            // Serve index.html and app.js from the /static directory on the
            // classpath (i.e. the ./static folder, since . is on the classpath).
            config.staticFiles.add("/static");

            // JSON endpoints. GET reads, POST appends.
            config.routes.get("/api/messages", s::handleGetMessages);
            config.routes.post("/api/messages", s::handlePostMessage);
        }).start(8331);
    }

    private void handleGetMessages(Context ctx) {
        ctx.json(messages);
    }

    private void handlePostMessage(Context ctx) {
        Message m = ctx.bodyAsClass(Message.class);
        if (m.name() != null && !m.name().isBlank()
                && m.message() != null && !m.message().isBlank()) {
            messages.add(m);
            System.out.println("Posted: " + m.name() + " - " + m.message());
        }
        // Return the updated list so the client can re-render in one round trip.
        ctx.json(messages);
    }
}
