package com.xhpc.evcs.http;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.util.Enumeration;

public class HttpServletRequestWritableWrapper extends HttpServletRequestWrapper implements HttpServletRequest {

    private final ByteArrayInputStream decryptedDataBAIS;

    public HttpServletRequestWritableWrapper(HttpServletRequest request, byte[] decryptedData) {

        super(request);
        decryptedDataBAIS = new ByteArrayInputStream(decryptedData);
    }

    @Override
    public String getHeader(String headerName) {

        String headerValue = super.getHeader(headerName);
        if (headerValue != null) {
            if ("Accept".equalsIgnoreCase(headerName)) {
                return headerValue.replaceAll(
                        MediaType.TEXT_PLAIN_VALUE, MediaType.APPLICATION_JSON_VALUE);
            } else if ("Content-Type".equalsIgnoreCase(headerName)) {
                return headerValue.replaceAll(
                        MediaType.TEXT_PLAIN_VALUE, MediaType.APPLICATION_JSON_VALUE);
            }
        }
        return headerValue;
    }

    @Override
    public Enumeration getHeaders(final String headerName) {

        return super.getHeaders(headerName);
    }

    @Override
    public String getContentType() {

        String contentTypeValue = super.getContentType();
        if (MediaType.TEXT_PLAIN_VALUE.equalsIgnoreCase(contentTypeValue)) {
            return MediaType.APPLICATION_JSON_VALUE;
        }
        return contentTypeValue;
    }

    @Override
    public BufferedReader getReader() throws UnsupportedEncodingException {

        return new BufferedReader(new InputStreamReader(decryptedDataBAIS, "UTF-8"));
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {

        return new ServletInputStream() {
            @Override
            public boolean isFinished() {

                return false;
            }

            @Override
            public boolean isReady() {

                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }

            @Override
            public int read() {

                return decryptedDataBAIS.read();
            }
        };
    }

}
