package dev.peerat.framework;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

public class TomcatHttpWriter extends HttpWriter{
	
	private HttpServletResponse response;
	private List<Output> senders;

	public TomcatHttpWriter(HttpServletResponse response) throws Exception{
		super();
		this.response = response;
		this.senders = new ArrayList<>();
	}
	
	@Override
	void response(int code, String... headers) throws Exception {
		response.setStatus(code);
		for(String header : headers){
			String[] split = header.split("\\s*:\\s*");
			response.setHeader(split[0], split[1]);
		}
	}
	
	@Override
	public void write(String message) throws IOException {
		this.senders.add((out) -> {
			PrintWriter writer = new PrintWriter(out);
			writer.write(message);
			writer.flush();
		});
	}
	
	@Override
	public void write(byte[] buffer) throws IOException{
		this.senders.add((out) -> {
			out.write(buffer);
			out.flush();
		});
	}
	
	@Override
	public void flush() throws IOException{
		if(out == null) return;
		flush(out);
	}
	
	private OutputStream out;
	
	public void free(OutputStream out){
		this.out = out;
	}
	
	public void flush(OutputStream out) throws IOException{
		for(Output sender : senders) sender.accept(out);
		senders.clear();
	}
	
	public static interface Output{
		
		void accept(OutputStream out) throws IOException;
		
	}
}
