package coreservlets.tags;

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;

/** Klasa obsługi znacznika makeTable. Klasa tworzy
 *  tabelę HTML i umieszcza w niej rekordy dwuwymiarowej
 *  tablicy przekazanej jako jeden z atrybutów znacznika
 *  w stronie JSP.
 *  <P>
 *  Taken from Core Servlets and JavaServer Pages Volume II
 *  from Prentice Hall and Sun Microsystems Press,
 *  http://volume2.coreservlets.com/.
 *  (C) 2007 Marty Hall, Larry Brown, and Yaakov Chaikin;
 *  may be freely used or adapted.
 */
public class MakeTableTag extends SimpleTagSupport {
  private Object[][] rowItems;
  private String headerClass;
  private String bodyClass;

  public void setRowItems(Object[][] rowItems) {
    this.rowItems = rowItems;
  }

  public void setHeaderClass(String headerClass) {
    this.headerClass = headerClass;
  }

  public void setBodyClass(String bodyClass) {
    this.bodyClass = bodyClass;
  }

  public void doTag() throws JspException, IOException {
    if (rowItems.length > 0) {
      JspContext context = getJspContext();
      JspWriter out = context.getOut();
      out.println("<TABLE BORDER=1>");
      Object[] headingRow = rowItems[0];
      printOneRow(headingRow, getStyle(headerClass), out);
      for(int i=1; i<rowItems.length; i++) {
        Object[] bodyRow = rowItems[i];
        printOneRow(bodyRow, getStyle(bodyClass), out);
      }
      out.println("</TABLE>");
    }
  }

  private void printOneRow(Object[] columnEntries,
                           String style,
                           JspWriter out)
      throws IOException {
    out.println("  <TR" + style + ">");
    for(int i=0; i<columnEntries.length; i++) {
      Object columnEntry = columnEntries[i];
      out.println("    <TD>" + columnEntry + "</TD>");
    }
    out.println("  </TR>");
  }

  private String getStyle(String className) {
    if (className == null) {
      return("");
    } else {
      return(" CLASS=\"" + headerClass + "\"");
    }
  }
}
