package com.buzzphone.server;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
import java.util.*;

// TODO: Investigate why the second (third etc) sessions only have one question?

/**
 * The WML servlet
 */
public class WMLTrivia extends HttpServlet {

  private static String fileroot;

  public void init () throws ServletException {
    try {
      Properties config = new Properties();
      config.load(this.getClass().getResourceAsStream("/config.properties"));
      fileroot = config.getProperty("DBFileRoot");
    } catch (Exception e) {
      e.printStackTrace();
      throw new ServletException("Property file error");
    }
  }

//  public void doPost (HttpServletRequest request,
//                    HttpServletResponse response)
//          throws ServletException, IOException {
//    doGet(request, response);
//  }

  public void service (HttpServletRequest request,
                       HttpServletResponse response)
          throws ServletException, IOException {

    response.setContentType("text/vnd.wap.wml");
    try {
      PrintWriter out = response.getWriter();
      out.println("<?xml version=\"1.0\" ?>");
      out.println("<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.1//EN\" \"http://www.wapforum.org/DTD/wml_1.1.xml\">");

      Class.forName("org.hsqldb.jdbcDriver");
      Connection c =
              DriverManager.getConnection ("jdbc:hsqldb:" +
                                           fileroot + "TriviaDB",
                                           "sa", "");
      c.setAutoCommit(true);
      Statement stmt =
              c.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                      ResultSet.CONCUR_READ_ONLY);
      ResultSet rs;

      HttpSession sess = request.getSession(true);
      String [] questionIds =
              (String []) sess.getAttribute("questionIds");
      String [] answers =
              (String []) sess.getAttribute("answers");

      if (questionIds == null || questionIds.length == 0) {

        rs = stmt.executeQuery("select id from Questions " +
                "where category='music01'");
        int count = 0;
        int i = 0;
        while (rs.next()) count++;
        questionIds = new String [count];
        answers = new String [count];
        for (i = 0; i < count; i++) {
          questionIds[i] = null;
          answers[i] = null;
        }
        rs.beforeFirst();
        i = 0;
        while (rs.next()) {
          questionIds[i] = rs.getString(1);
          i++;
        }
        sess.setAttribute("questionIds", questionIds);
        sess.setAttribute("answers", answers);
      }


      String ans = request.getParameter("ans");
      if (ans != null && !"".equals(ans)) {
        String qId = ans.substring(0, ans.indexOf(','));
        String aId = ans.substring(ans.indexOf(',')+1);
        for (int i = 0; i < questionIds.length; i++) {
          if ( questionIds[i].equals(qId) ) {
            answers[i] = aId;
            break;
          }
        }
      }

      int pos = 0;
      for (pos = 0; pos < questionIds.length; pos++) {
        if (answers[pos] == null) break;
      }

      if ( pos != questionIds.length ) {
        // Present the next question
        String questionId = questionIds[pos];
        rs = stmt.executeQuery("select question from Questions " + "" +
                "where id=" + questionId);
        rs.next();
        String question = rs.getString(1);
        rs = stmt.executeQuery("select choiceId, choice from Choices " +
          "where questionId=" + questionId + " order by choiceId ASC");

        out.println("<wml>");
        out.println("<card id=\"start\" title=\"question\">");
        out.println("<p>" + question +
         "(Check out the picture <a href=\"#imagecard\">here</a></p>");
        while (rs.next()) {
          String choiceId = rs.getString(1);
          String choice = rs.getString(2);

          out.println("<p><a href=\"" +
                  response.encodeURL("WMLTrivia?ans=" +
                  questionId + "," +
                  choiceId) + "\">" + choiceId + " " +
                  choice + "</a></p>");
        }
        out.println("</card>");
        out.println("<card id=\"imagecard\" title=\"image\">");
        out.println("<p><img src=\"/Trivia/database/gif/" + questionId +
                ".gif\" alt=\" \" /></p>");
        out.println("</card>");
        out.println("</wml>");

      } else {
        // Show results
        int correctNum = 0;
        PreparedStatement pstmt =
                c.prepareStatement("select id from Questions " +
                "where id=? and answerId=?");
        for (int i = 0; i < questionIds.length; i++) {
          pstmt.setString(1, questionIds[i]);
          pstmt.setString(2, answers[i]);
          rs = pstmt.executeQuery();
          if (rs.next()) correctNum++;
        }
        pstmt.close();

        out.println("<wml>");
        out.println("<card id=\"start\" title=\"result\">");
        out.println("<p>You got " + correctNum +
                " correct answers out of " + questionIds.length +
                " questions</p>");
        out.println("<p><a href=\"WMLTrivia\">Start a new session</a></p>");
        out.println("</card>");
        out.println("</wml>");
      }

      stmt.close();
      c.close();
      out.close();

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
