package com.eactive.eai.adapter.socket2.protocol.http.codec;

import com.eactive.eai.adapter.socket2.protocol.http.Server;
import org.apache.mina.common.ByteBuffer;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;


public class HttpResponse {
    /** HTTP response codes */
    public static final int HTTP_STATUS_SUCCESS = 200;

    public static final int HTTP_STATUS_NOT_FOUND = 404;

    /** Map<String, String> */
    private Map<String, String> headers = new HashMap<String, String>();

    /** Storage for body of HTTP response. */
    private ByteArrayOutputStream body = new ByteArrayOutputStream(1024);

    private int responseCode = HTTP_STATUS_SUCCESS;

    public HttpResponse() {
        headers.put("Server", "HttpServer (" + Server.VERSION_STRING + ')');
        headers.put("Cache-Control", "private");
        headers.put("Content-Type", "text/html; charset='UTF-8'");
        headers.put("Connection", "keep-alive");
        headers.put("Keep-Alive", "200");
        headers.put("Date", DateTimeFormatter.ofPattern(
                "EEE, dd MMM yyyy HH:mm:ss zzz").format(ZonedDateTime.now()));
        headers.put("Last-Modified", DateTimeFormatter.ofPattern(
                "EEE, dd MMM yyyy HH:mm:ss zzz").format(ZonedDateTime.now()));
    }

    public Map getHeaders() {
        return headers;
    }
    
    public void addHeader(String key, String value) {
    	headers.put(key, value);
    }

    public void setContentType(String contentType) {
        headers.put("Content-Type", contentType);
    }

    public void setResponseCode(int responseCode) {
        this.responseCode = responseCode;
    }

    public int getResponseCode() {
        return this.responseCode;
    }

    public void appendBody(byte[] b) {
        try {
            body.write(b);
        } catch (IOException ex) {
            // System.out.println("appendBody error");
        }
    }

    public void appendBody(String s) {
        try {
            body.write(s.getBytes());
        } catch (IOException ex) {
        	// System.out.println("appendBody string error");
        }
    }

    public ByteBuffer getBody() {
        return ByteBuffer.wrap(body.toByteArray());
    }

    public int getBodyLength() {
        return body.size();
    }
}
