package core.processor;

import com.sun.net.httpserver.HttpExchange;
import core.utils.io.TemplateReader;
import core.utils.logs.Logger;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.sql.SQLException;

public abstract class Processor
{
    protected final TemplateReader reader = new TemplateReader();

    public abstract void process(HttpExchange exchange) throws IOException, SQLException;

    protected void process(HttpExchange exchange, String response)
    {
        try(PrintWriter writer = writer(exchange))
        {
            Logger.info(exchange);

            exchange.getResponseHeaders().add("Content-Type", "text/html; charset=utf-8");
            exchange.sendResponseHeaders(200, response.length());

            writer.write(response);
            writer.flush();
        }
        catch (IOException exception)
        {
            Logger.error(exception.getMessage());
        }
    }

    private PrintWriter writer(HttpExchange exchange)
    {
        OutputStream stream = exchange.getResponseBody();
        Charset charset = StandardCharsets.UTF_8;

        return new PrintWriter(stream, false, charset);
    }
}
