
package org.jboss.as.quickstarts.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.microprofile.reactive.messaging.Channel;
import org.eclipse.microprofile.reactive.messaging.Emitter;

import jakarta.enterprise.context.ApplicationScoped;

/**
 * Definition of the JMS destination used by the quickstart (one queue).
 * The topic definition is omitted as it is not addressed in the static code analysis issue.
 */
@ApplicationScoped
@WebServlet("/HelloWorldMDBServletClient")
public class HelloWorldMDBServletClient extends HttpServlet {

    private static final long serialVersionUID = -8314035702649252239L;

    private static final int MSG_COUNT = 5;

    @Inject
    @Channel("HELLOWORLDMDBQueue")
    Emitter<String> queueEmitter;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html");
        PrintWriter out = resp.getWriter();
        out.write("<h1>Quickstart: Example demonstrates the use of <strong>MicroProfile Reactive Messaging</strong> in Quarkus.</h1>");
        try {
            boolean useTopic = req.getParameterMap().keySet().contains("topic");
            if (useTopic) {
                // If the application still needs to support topics, additional logic will be required here.
                // This could involve injecting another Emitter for the topic or handling it differently.
                throw new UnsupportedOperationException("Topic messaging not supported in this example.");
            }

            out.write("<p>Sending messages to <em>HELLOWORLDMDBQueue</em></p>");
            out.write("<h2>The following messages will be sent to the queue:</h2>");
            for (int i = 0; i < MSG_COUNT; i++) {
                String text = "This is message " + (i + 1);
                queueEmitter.send(text);
                out.write("Message (" + i + "): " + text + "</br>");
            }
            out.write("<p><i>Go to your Quarkus server console or server log to see the result of messages processing.</i></p>");
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
