import java.util.List;
import java.util.ArrayList;
import java.io.*;
import java.sql.*;
import javax.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.struts.action.*;
import jp.ac.wakhok.library.*;

public class SearchBookAction extends Action {

	public ActionForward execute(
		ActionMapping mapping, ActionForm f,
		HttpServletRequest request, HttpServletResponse response) {

		SearchForm form = (SearchForm)f;
		String ndc           = form.getNdc();
		String tyosya_hyouji = form.getTyosya_hyouji();
		String id            = form.getId();
		String title         = form.getTitle();
		String author        = form.getAuthor();
		String publisher     = form.getPublisher();

		List list =
			search(ndc, tyosya_hyouji, id, title, author, publisher);

		HttpSession session = request.getSession();
		session.setAttribute("bookList", list);

		return(mapping.findForward("success"));
	}

	private List search(String ndc, String tyosya_hyouji,
							String id, String title,
							String author, String publisher) {
		List list = new ArrayList();
		try {
			Class.forName("org.hsqldb.jdbcDriver");
			String url = "jdbc:hsqldb:hsql://localhost";
			Connection con = DriverManager.getConnection(url, "sa", "");

			String selectStatement =
				"select * " +
				"from books where ndc           like ? " +
				             "and tyosya_hyouji like ? " +
				             "and id            like ? " +
				             "and title         like ? " +
				             "and author        like ? " +
				             "and publisher     like ? ";
			PreparedStatement prepStmt =
				con.prepareStatement(selectStatement);
			prepStmt.setString(1, appendPercent(ndc));
			prepStmt.setString(2, appendPercent(tyosya_hyouji));
			prepStmt.setString(3, appendPercent(id));
			prepStmt.setString(4, appendPercent(title));
			prepStmt.setString(5, appendPercent(author));
			prepStmt.setString(6, appendPercent(publisher));

			ResultSet rs = prepStmt.executeQuery();
			while (rs.next()) {
				BookData book = new BookData();
				book.setNdc(rs.getString("ndc"));
				book.setTyosya_hyouji(rs.getString("tyosya_hyouji"));
				book.setId(rs.getString("id"));
				book.setTitle(rs.getString("title"));
				book.setAuthor(rs.getString("author"));
				book.setPublisher(rs.getString("publisher"));
				list.add(book);
			}
			prepStmt.close();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}

		return list;
	}

	private String appendPercent(String from) {
		StringBuffer to = new StringBuffer();
		to.append("%");
		to.append(from);
		to.append("%");

		return new String(to);
	}
}
