package com.atlassian.stash.rest.webhook;

import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;

/**
 * Servlet that receives and records webhooks. Used by the webhook tests to verify that the webhooks have fired
 */
public class WebHookCallbackServlet extends HttpServlet {

    private List<String> webHooks = new ArrayList<>();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String testAction = req.getParameter("test-action");
        if (testAction != null) {
            switch (testAction) {
                case "clear":
                    webHooks.clear();
                    break;
                default:
                    resp.getWriter().write("Unknown action " + testAction);
            }
        } else {
            webHooks.add(IOUtils.toString(req.getInputStream()));
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String delim = "\n";
        Writer writer = resp.getWriter();
        writer.write("{\"web-hooks\":[");
        for (String hook : webHooks) {
            writer.write(delim);
            writer.write(hook);
            delim = ",\n";
        }
        writer.write("]}");
    }
}
