package local.web;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@WebServlet(name = "HelloServlet", urlPatterns = {"/hello"})
public class HelloServlet extends HttpServlet {

    private final static Logger logger = LoggerFactory.getLogger(HelloServlet.class);

    @Resource(name = "jdbc/UsersDB")
    private DataSource dataSource;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        PrintWriter writer = res.getWriter();

        try (Connection conn = dataSource.getConnection()) {

            try (Statement statement = conn.createStatement()) {
                String sql = "SELECT username, email FROM users";

                try (ResultSet rs = statement.executeQuery(sql)) {

                    int count = 1;
                    logger.info("count: {}", count);
                    while (rs.next()) {
                        writer.println(String.format("User #%d: %-15s %s", count++,
                                rs.getString("username"), rs.getString("email")));

                    }
                }
            }

        } catch (SQLException ex) {
            logger.error("error", ex);
        }
    }
}
