{% extends 'base.html' %}

{% block content %}

    <h2>Start exam: {{ exam }}</h2>

    {% if exam.time_limit %}
        This exam has a time limit of {{ exam.get_time_limit }}. The time will start when you click the Start Exam button below.<br/>
    {% endif %}

    {% if request.user.is_authenticated and valid_user %}
        <a href="{% url 'sbas:exam_take_user' pk=exam.pk sk=0 %}" title="Click to start the exam"><button class="btn btn-primary">Start Exam</button></a>
    {% else %}
        Enter your CID and passcode in the below boxes.<br />
        <p><input id="cid-box" type="text" value="Candidate ID"></p>
        <p><input id="passcode-box" type="text" value="Passcode"></p>

        <button type="button" class="btn btn-primary">Start exam</button>

        <script type="text/javascript">
            $(document).ready(function () {
                window.location.search.substr(1).split("&").forEach((item) =>
                    {
                        s = item.split("=");
                        if (s[0] == "cid") {
                            $("#cid-box").val(s[1]);

                        }
                        if (s[0] == "passcode") {
                            $("#passcode-box").val(s[1]);
                        }
                    });

                $("#cid-box, #passcode-box").keypress(function(e) {
                // Enter pressed?
                    console.log(e)
                    if(e.which == 10 || e.which == 13) {
                        $("button").click();
                    }
                });

                $("button").click(() => {
                    let cid = $("#cid-box").val();
                    let passcode = $("#passcode-box").val();

                    if (Number.isInteger(parseInt(cid))) {
                        // reverse a URL with safe placeholders and replace them client-side
                        const template = "{% url 'sbas:exam_take' pk=exam.pk sk=0 cid=0 passcode='0' %}"; // e.g. /sbas/exam/1/0/0/0/take
                        const url = template.replace('/0/0/take', `/${cid}/${passcode}/take`);
                        window.location.replace(url);
                    } else {
                        alert("Please enter a valid Candidate ID (CID).")
                    }
                });
            });
        </script>
    {% endif %}

    {% include "sbas/exam_take_help.html" %}

{% endblock %}