package bean;
import java.sql.*;
import java.util.*;
import javax.naming.*;
import javax.sql.DataSource;

public class Dept implements java.io.Serializable {

  private String name;
  private int id;

  private static final String select = "select deptid, name " +
                                       "from dept";
  private static final String selectEmployee =
           "select empid, fname, lname, phone, deptid" +
           " from employee where deptid=? " +
           " order by lname";

  public Dept() {
  }

  public Dept(ResultSet rs) throws SQLException{
    init(rs);
  }

  public void init(ResultSet rs) throws SQLException{
    this.name = rs.getString("name");
    this.id = rs.getInt("deptid");
  }

  public String getName() {
    return this.name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public int getId() {
    return this.id;
  }

  public void setId(int id) {
    this.id = id;
  }

  static Connection getConnection(){
    try {
        Context initCtx = new InitialContext();
        Context envCtx = (Context) initCtx.
        lookup("java:comp/env");
        DataSource ds = (DataSource) envCtx.lookup("jdbc/emp");
        return ds.getConnection();
    }catch (Exception e){
        e.printStackTrace();
    }

    }
    catch (Exception e){
    }
  }

  public static Dept [] getDepartments()throws SQLException{

    Connection connection = null;
    Statement statement = null;
    ResultSet resultSet = null;
    ArrayList depts = new ArrayList();

    try{

        connection = getConnection();
        statement = connection.createStatement();
        resultSet = statement.executeQuery(select);

        while(resultSet.next()){
          Dept dept = new Dept(resultSet);
          depts.add(dept);
        }
    }finally {
        if (resultSet!=null) resultSet.close();
        if (statement!=null) statement.close();
        if (connection!=null) connection.close();
      }

      Dept [] arrayDepts = new Dept[depts.size()];
      return (Dept []) depts.toArray(arrayDepts);

    }

    public Employee [] getEmployees() throws SQLException{

      Connection connection = null;
      PreparedStatement statement = null;
      ResultSet resultSet = null;
      ArrayList emps = new ArrayList();

      try{

          connection = getConnection();
          statement = connection.prepareStatement(selectEmployee);
          statement.setInt(1, this.id);

          resultSet = statement.executeQuery();

          while(resultSet.next()){
            Employee emp = new Employee(resultSet);
            emps.add(emp);
          }

      }finally {
         if (resultSet!=null) resultSet.close();
         if (statement!=null) statement.close();
         if (connection!=null) connection.close();
      }

      Employee [] arrayEmps = new Employee[emps.size()];
      return (Employee []) emps.toArray(arrayEmps);
  }
}
