package ru.yandex.qe.jetty.server;

import org.apache.commons.io.Charsets;
import org.eclipse.jetty.http.HttpFields;
import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.http.HttpMethod;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.http.MimeTypes;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Response;
import org.eclipse.jetty.server.handler.ErrorHandler;
import org.eclipse.jetty.util.BufferUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.ByteBuffer;

/**
 * @author lvovich
 */
public class TextPlainErrorHandler extends ErrorHandler {

    /* ------------------------------------------------------------ */
    /*
     * @see org.eclipse.jetty.server.server.Handler#handle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, int)
     */
    @Override
    public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException
    {
        String method = request.getMethod();
        if (!HttpMethod.GET.is(method) && !HttpMethod.POST.is(method) && !HttpMethod.HEAD.is(method))
        {
            baseRequest.setHandled(true);
            return;
        }

        baseRequest.setHandled(true);
        response.setContentType(MimeTypes.Type.TEXT_PLAIN_UTF_8.asString());
        if (getCacheControl()!=null)
            response.setHeader(HttpHeader.CACHE_CONTROL.asString(), getCacheControl());
        ByteArrayOutputStream baos = new ByteArrayOutputStream(4096);
        Writer writer= new OutputStreamWriter(baos, Charsets.UTF_8);
        String reason=(response instanceof Response)?((Response)response).getReason():null;
        handleErrorPage(request, writer, response.getStatus(), reason);
        writer.flush();
        response.setContentLength(baos.size());
        baos.writeTo(response.getOutputStream());
    }

    /* ------------------------------------------------------------ */
    protected void handleErrorPage(HttpServletRequest request, Writer writer, int code, String message)
        throws IOException
    {
        writeErrorPage(request, writer, code, message, isShowStacks());
    }

    /* ------------------------------------------------------------ */
    protected void writeErrorPage(HttpServletRequest request, Writer writer, int code, String message, boolean showStacks)
        throws IOException
    {
        if (message == null)
            message= HttpStatus.getMessage(code);

        writeErrorPageBody(request,writer,code,message,showStacks);
    }

    /* ------------------------------------------------------------ */
    protected void writeErrorPageBody(HttpServletRequest request, Writer writer, int code, String message, boolean showStacks)
        throws IOException
    {
        String uri= request.getRequestURI();

        writeErrorPageMessage(request,writer,code,message,uri);
        if (showStacks)
            writeErrorPageStacks(request,writer);
    }

    /* ------------------------------------------------------------ */
    protected void writeErrorPageMessage(HttpServletRequest request, Writer writer, int code, String message,String uri)
    throws IOException
    {
        writer.write("HTTP ERROR ");
        writer.write(Integer.toString(code));
        writer.write(": Problem accessing ");
        writer.write(uri);
        writer.write(". Reason:  ");
        writer.write(message);
    }

    /* ------------------------------------------------------------ */
    protected void writeErrorPageStacks(HttpServletRequest request, Writer writer)
        throws IOException
    {
        Throwable th = (Throwable)request.getAttribute("javax.servlet.error.exception");
        if (th != null) {
            writer.write("\nCaused by: ");
            writer.write(th.toString());
        }
    }

    /* ------------------------------------------------------------ */
    /** Bad Message Error body
     * <p>Generate a error response body to be sent for a bad message.
     * In this case there is something wrong with the request, so either
     * a request cannot be built, or it is not safe to build a request.
     * This method allows for a simple error page body to be returned
     * and some response headers to be set.
     * @param status The error code that will be sent
     * @param reason The reason for the error code (may be null)
     * @param fields The header fields that will be sent with the response.
     * @return The content as a ByteBuffer, or null for no body.
     */
    public ByteBuffer badMessageError(int status, String reason, HttpFields fields)
    {
        if (reason==null)
            reason=HttpStatus.getMessage(status);
        fields.put(HttpHeader.CONTENT_TYPE,MimeTypes.Type.TEXT_PLAIN_8859_1.asString());
        return BufferUtil.toBuffer("Bad Message " + status + ", reason: " + reason);
    }

}
