package serwlety;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

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;

@WebServlet("/ZwyklyOdczyt")
public class ZwyklyOdczyt extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	@Resource(lookup="java:/HR_DS")
	private DataSource dataSource;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		response.setContentType("text/plain");
		response.setCharacterEncoding("utf-8");
		
		PrintWriter out = response.getWriter();
		out.println("dataSource = " + dataSource);

		try(Connection c = dataSource.getConnection();
			Statement stmt = c.createStatement();
			ResultSet rs = stmt.executeQuery("SELECT * FROM employees")) {
			
			while(rs.next()) {
				String fname = rs.getString("first_name");
				String lname = rs.getString("last_name");
				
				int dep_id = rs.getInt("department_id");
				BigDecimal salary = rs.getBigDecimal("salary");
				
				out.printf("* %-12s %-12s (dep. %3d) zarabia %8s%n", fname, lname, dep_id, salary);
			}
		} catch (SQLException e) {
			e.printStackTrace(out);
		}
	}
}
