<%@ page import="java.sql.*" %>
<%@ page import="com.buzzphone.server.WML.*" %>

<?xml version="1.0" ?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.1//EN"
                     "http://www.wapforum.org/DTD/wml_1.1.xml">

<% response.setContentType("text/vnd.wap.wml"); %>

<%
  // Handle session related issues
  HttpSession sess = request.getSession(true);
  String [] questionIds =
              (String []) sess.getAttribute("questionIds");
  String [] answers =
              (String []) sess.getAttribute("answers");
  // If no session exists ...
  if (questionIds == null || questionIds.length == 0) {
    questionIds = TriviaHelper.getQuestions("music01");
    answers = new String [questionIds.length];
    for (int i = 0; i < questionIds.length; i++) {
      answers[i] = null;
    }
    sess.setAttribute("questionIds", questionIds);
    sess.setAttribute("answers", answers);
  }

  // Store the last answer if any
  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;
      }
    }
  }

  // Find out the next question index
  int pos = 0;
  for (pos = 0; pos < questionIds.length; pos++) {
    if (answers[pos] == null) break;
  }

  if (pos == questionIds.length) {
    // results
    String result = TriviaHelper.getResult(questionIds, answers);
%>

<wml>
  <card id="start" title="result">
    <p>You got <%=result%></p>
    <p><a href="WMLTrivia.jsp">Start a new session</a></p>
  </card>
</wml>

<%
  } else {
    // The next question
    String questionId = questionIds[pos];
    TriviaQuestion tq = new TriviaQuestion(questionId);
%>

<wml>
  <card id="start" title="question">
    <p><%=tq.question%> (Check out the picture <a href="#imagecard">here</a></p>
<%
    for (int i = 0; i < tq.choices.length; i++) {
      int choiceId = i + 1;
      String encodedURL = response.encodeURL("WMLTrivia.jsp?ans=" +
                                         questionId + "," + choiceId);
%>
    <p><a href="<%=encodedURL%>">
    <%=i+1%> <%=tq.choices[i]%></a></p>
<%
    }
%>
  </card>
  <card id="imagecard" title="image">
    <p><img src="/Trivia/database/gif/<%=questionId%>.gif" alt=" "/></p>
  </card>
</wml>
<%
  }
%>