/*
 * Copyright (c) 2004-2017, by Alex Leigh.
 * All rights reserved.
 *
 * THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE
 * The copyright notice above does not evidence any
 * actual or intended publication of such source code.
 */

package lc.mecha.http.server;

import lc.mecha.fabric.HandlerStatus;

import java.util.Set;

/**
 * A handy version of the <code>PrefixedHandler</code> that breaks out the methods based
 * on the HTTP method used in the request. If the method does not match GET, POST, PUT or
 * DELETE, an error 500 is thrown using the default error interface.
 *
 * @author Alex Leigh
 */
public abstract class MultiMethodHandler extends PrefixedHandler {
    public MultiMethodHandler(final Set<String> pathPrefix) {
        super(pathPrefix);
    }

    public HandlerStatus handlePrefixedWebRequest(final HttpTransaction request) throws Throwable {
        switch (request.httpServletRequest.getMethod()) {
            case "GET":
                return handleGetRequest(request);
            case "POST":
                return handlePostRequest(request);
            case "PUT":
                return handlePutRequest(request);
            case "DELETE":
                return handleDeleteRequest(request);
        }

        request.httpServletResponse.sendError(500);
        return HandlerStatus.BREAK;
    }

    /**
     * Default implementation which throws a 405 error. Replace with a useful implementation.
     *
     * @param request
     * @return
     * @throws Throwable
     */
    public HandlerStatus handleGetRequest(final HttpTransaction request) throws Throwable {
        request.httpServletResponse.sendError(405);
        return HandlerStatus.BREAK;
    }

    /**
     * Default implementation which throws a 405 error. Replace with a useful implementation.
     *
     * @param request
     * @return
     * @throws Throwable
     */
    public HandlerStatus handlePostRequest(final HttpTransaction request) throws Throwable {
        request.httpServletResponse.sendError(405);
        return HandlerStatus.BREAK;
    }

    /**
     * Default implementation which throws a 405 error. Replace with a useful implementation.
     *
     * @param request
     * @return
     * @throws Throwable
     */
    public HandlerStatus handlePutRequest(final HttpTransaction request) throws Throwable {
        request.httpServletResponse.sendError(405);
        return HandlerStatus.BREAK;
    }

    /**
     * Default implementation which throws a 405 error. Replace with a useful implementation.
     *
     * @param request
     * @return
     * @throws Throwable
     */
    public HandlerStatus handleDeleteRequest(final HttpTransaction request) throws Throwable {
        request.httpServletResponse.sendError(405);
        return HandlerStatus.BREAK;
    }
}
