package com.atlassian.stash.internal.plugin;

import com.atlassian.bitbucket.nav.NavBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.HttpRequestHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component("streamsEmptyActivityServlet")
public class StreamsEmptyActivityServlet implements HttpRequestHandler {
    private final NavBuilder navBuilder;

    @Autowired
    public StreamsEmptyActivityServlet(NavBuilder navBuilder) {
        this.navBuilder = navBuilder;
    }

    @Override
    public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setStatus(200);
        StringBuilder builder = new StringBuilder();
        if (request.getRequestURI().contains("plugins/servlet/streams")) {
            response.addHeader("Content-Type", "text/xml");
            builder.
                    append("<feed xmlns=\"http://www.w3.org/2005/Atom\">").
                    append("    <title type=\"text\">Activity Streams</title>").
                    append("    <subtitle type=\"text\">Activity Streams</subtitle>").
                    append("    <link href=\"").
                    append(navBuilder.buildAbsolute()).
                    append("/plugins/servlet/streams\" rel=\"self\" />").
                    append("</feed>");
        } else {
            response.addHeader("Content-Type", "application/json");
            builder.
                    append("{").
                    append("    \"filters\" : [  ]").
                    append("}");
        }

        response.getWriter().append(builder.toString());
    }
}
