<%# Page to display questions on for classic training %>
<%# ARGUMENTS: question - question object %>

<%- include("../../partials/header") -%>
<%- include("../../partials/navigationPrivate") -%>

<%# JS code %>
<script>
  $(document).ready(function() {
    // declare useful helper method
    function arraysEqual(a, b) {
      if (a === b) return true;
      if (a == null || b == null) return false;
      if (a.length !== b.length) return false;

      for (let i = 0; i < a.length; ++i) {
        if (a[i] !== b[i]) return false;
      }
      return true;
    }

    // decheck all checkboxes/radio buttons
    $('.form-check-input').prop('checked', false);

    // hide all flashes and answer explanation upon loading
    $('#correct').hide(0);
    $('#wrong').hide(0);
    $('#answer').hide(0);

    // configure check answer button
    $('#submit').click(() => {
      let correct = false;
      const type = $('#hiddenType').val();

      let correctAnswer = $('#hiddenAnswer').val().split('@');
      let numOfChoices = parseInt($('#numOfChoices').val());
      if (type == 'mc') {
        let userAnswer = 0;
        for (i = 1; i <= numOfChoices; i++) {
          if ($('#' + i).is(':checked')) {
            userAnswer = i;
          }
        }

        if (correctAnswer[0] == userAnswer) {
          correct = true;
        }
      } else if (type == 'sa') {
        let userAnswer = [];
        for (i = 1; i <= numOfChoices; i++) {
          if ($('#' + i).is(':checked')) {
            userAnswer.push('' + i);
          }
        }

        if (arraysEqual(userAnswer, correctAnswer)) {
          correct = true;
        }
      } else if (type == 'fr') {
        let userAnswer = $('#fr-answer').val();
        if (userAnswer.trim().toLowerCase() == correctAnswer[0].toLowerCase()) {
          correct = true;
        }
      }

      if (correct) {
        $('#wrong').hide(0);
        $('#correct').show(500);
        $('#answer').show(500);
      } else {
        $('#wrong').show(500);
        $('#correct').hide(0);
        if (type == 'fr') {
          setTimeout(() => $('#fr-answer').focus(), 0);
        }
      }
    });

    // configure give up button
    $('#give-up').click(() => {
      $('#wrong').show(500);
      $('#correct').hide(0);
      $('#answer').show(500);
    });

    $('#fr-answer').keypress((e) => {
      if ((e.keyCode || 0) === 13) {
        $('#submit').click();
        return false;
      }
    });
  });
</script>


<div class="jumbotron container mt-5">
  <% try { %>

  <%# Test for faulty question %>
  <% if (!question) { %>
  <% throw "no question found"; %>
  <% } %>
  <% if((question.question == "") || (question.rating == null) || (question.answer[0] == "") || (question.answerEx == "")) { %>
  <% throw "bad question parameters"; %>
  <% } %>

  <h1 class="display-3 text-center">Daily Question</h1>
  <table class="text-center table mt-3">
    <thead>
      <tr>
        <th scope="col">Date</th>
        <th scope="col">Subject</th>
        <th scope="col">Rating</th>
        <th scope="col">Passrate</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td><%= new Date().toISOString().split('T')[0] %></td>
        <td><%= question.subject[0] %></td>
        <td><%= question.rating %></td>
        <td><%= Math.round(100*(question.stats.pass)/(question.stats.pass+question.stats.fail)) %>%</td>
      </tr>
    </tbody>
  </table>

  <div class="row">
    <div class="col-1"></div>

    <div class="col-10">
      <p class="lead mb-3">
        <% if(question.ext_source != "original") { %>
      <p>Question Source: <%= question.ext_source %></p>
      <p><%= question.source_statement %></p>
      <% } %>
      </p>

      <%# Display question %>
      <% if(question.type == "mc") { %>

      <%# Multiple choice %>

      <h3 class="display-4" style="font-size: 1.5rem;">Please read the following question and select the best answer:</h3>
      <p><%- question.question %></p>

      <div class="mt-4" id="mc-choices">
        <% var choiceIndex = 1; %>
        <% question.choices.forEach((choice) => { %>
        <div class="form-check">
          <input class="form-check-input" type="radio" name="answerChoice" id="<%= choiceIndex %>" value="<%= choiceIndex %>">
          <label class="form-check-label" for="<%= choiceIndex %>"><%= String.fromCharCode(64+choiceIndex) %>. <%= choice %></label>
          <% choiceIndex++; %>
        </div>
        <% }) %>
      </div>

      <% } else if(question.type == "sa") { %>

      <%# Select all %>

      <h3 class="display-4" style="font-size: 1.5rem;">Please read the following and select ALL choices that apply:</h3>
      <p><%- question.question %></p>

      <div class="mt-4" id="sa-choices">
        <% var choiceIndex = 1; %>
        <% question.choices.forEach((choice) => { %>
        <div class="form-check my-1 me-sm-2">
          <input type="checkbox" name="saChoice" class="form-check-input" id="<%= choiceIndex %>" value="<%= choiceIndex %>">
          <label class="form-check-label" for="<%= choiceIndex %>"><%= String.fromCharCode(64+choiceIndex) %>. <%= choice %></label>
        </div>
        <% choiceIndex++; %>
        <% }) %>
      </div>

      <% } else if(question.type == "fr") { %>

      <%# Free response %>

      <h3 class="display-4" style="font-size: 1.5rem;">Please read the following question and enter your answer in the box:</h3>
      <p><%- question.question %></p>

      <div class="mt-4">
        <div class="form-group">
          <input type="text" class="form-control" id="fr-answer" placeholder="Enter your answer here" name="freeAnswer" value="">
        </div>
      </div>

      <% } else { %>
      <% throw "invalid type"; %>
      <% } %>

      <input class="btn btn-primary my-3" type="button" value="Check Answer" id="submit">
      <input class="btn btn-link mb-3 float-end" type="button" value="Give up" id="give-up">

      <input type="hidden" id="hiddenID" value="<%= question._id %>">
      <input type="hidden" id="hiddenType" value="<%= question.type %>">
      <input type="hidden" id="hiddenAnswer" value="<%= question.answer.join('@') %>">
      <input type="hidden" id="numOfChoices" value="<%= question.choices.length %>">

      <div class="alert alert-success" id="correct">Your answer is correct!</div>
      <div class="alert alert-danger" id="wrong">Your answer is incorrect!</div>

      <div class="mt-5" id="answer">
        <% if(question.type == "mc") { %>

        <h5>The correct answer is: <%= String.fromCharCode(64+parseInt(question.answer[0])) %></h5>
        <% } else if(question.type == "sa") { %>

        <% let answerString = ""; %>
        <% let index = 1; %>
        <% question.answer.forEach((answer) => { %>
        <% answerString += answer != question.answer.length ? (String.fromCharCode(64+parseInt(answer)) + ", ") : String.fromCharCode(64+parseInt(answer)); %>
        <% index++; %>
        <% }) %>

        <h5>The correct answer is: <%= answerString %></h5>
        <% } else if(question.type == "fr") { %>

        <h5>The correct answer is: <%= question.answer[0] %></h5>
        <% } %>

        <h3>Answer Explanation:</h3>
        <p><%- question.answer_ex %></p>
      </div>
    </div>

    <div class="col-1"></div>
  </div>

  <% } catch(err) { %>

  <!-- ERROR CODE -->
  <% if(err=="bad question parameters") { %>
  <h3>Someone messed up their equations! Perhaps they said $\sin^2(\theta)+\cos^2(\theta) \neq 1$ ?</h3>
  <p>Sorry, we could not display your question. Please reenter the trainer and inform an admin that the question with ID <font color="red"><%= question._id %></font> is dysfunctional.</p>

  <% } else { %>
  <h3>Daily question unavailable.</h3>
  <p>Oops we don't know what happened... tell an admin that the daily question page is broken!</p>

  <a href="/train" class="btn btn-primary w-100 btn-lg mt-4">Click me to go back</a>
  <% } %>

  <% } %>
</div>

<%- include("../../partials/footer") -%>
