package org.warb.vds;

import java.io.IOException;

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

import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.server.VaadinServlet;
import com.vaadin.shared.ApplicationConstants;

/**
 * This servlet calls the VDS UI only. If a view is not found it sends a 404 response before instantiating the UI.
 */
@WebServlet(value = "/vds/*",
        asyncSupported = true)
@VaadinServletConfiguration(
        productionMode = false,
        ui = ViewDispatchUI.class)
public class ViewDispatchServlet extends VaadinServlet {
    private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(ViewDispatchServlet.class);

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String pathInfo = request.getPathInfo();
        if (pathInfo != null && (isVaadinPath(pathInfo) || ViewMap.getViewClass(pathInfo) != null)) {
            super.service(request, response);
        } else {
            log.error("Sending 404 for pathinfo [" + pathInfo + "]");
            response.sendError(404);
        }
    }

    /**
     * Allow Vaadin internal paths to work unencumbered.
     * @param pathInfo
     * @return
     */
    private boolean isVaadinPath(String pathInfo) {
        return pathInfo.startsWith("/" + ApplicationConstants.APP_PATH) ||
               pathInfo.startsWith("/" + ApplicationConstants.UIDL_PATH) ||
               pathInfo.startsWith("/" + ApplicationConstants.HEARTBEAT_PATH) ||
               pathInfo.startsWith("/" + ApplicationConstants.PUSH_PATH);
    }
}
