{% extends 'generic/base.html' %}

{% load crispy_forms_tags %}
{% block css %}
{% endblock %}

{% block content %}

Trainees can be viewed <a href='{% url "trainees" %}'>here</a> (
    
    {% for i in "123456"|make_list %}
    <a href='{% url "trainees_grade" "ST"|add:i %}'>ST{{i}}</a>{% if not forloop.last %}, {% endif %}
    {% endfor %}
    )

<div class="card border-secondary bg-dark text-white mb-4 mt-3">
    <div class="card-body">
        <h4 class="card-title mb-3"><i class="bi bi-search me-2"></i>Quick User Search</h4>
        <div class="row align-items-center g-2">
            <div class="col-12 col-md-8">
                <div class="input-group">
                    <span class="input-group-text bg-secondary border-secondary text-white"><i class="bi bi-search"></i></span>
                    <input type="search"
                           name="q"
                           class="form-control bg-dark text-white border-secondary"
                           placeholder="Search users by name, email, or username..."
                           hx-get="{% url 'people' %}"
                           hx-trigger="input delay:300ms, search"
                           hx-target="#search-results"
                           hx-indicator="#search-indicator">
                </div>
            </div>
            <div class="col-auto">
                <span id="search-indicator" class="spinner-border spinner-border-sm text-light htmx-indicator" role="status" aria-hidden="true"></span>
            </div>
        </div>
        <div id="search-results" class="mt-3"></div>
    </div>
</div>

<h2>People</h2>
<p>The system contains a number of different people / groups. This affects how they are managed and what they are able to do.</p>
<p>They can be managed using the navigation links above</p>

<h3>User(s)</h3>
<p>Users on the system have a registered account. This allows them to log in to browse the site. In most cases they will be able to creeate and manage exams / packets as well as take those that they have been given access to.</p>

<p>All South West (internal) trainees should have an account. This allows for easier management as they can be grouped by grade, can be associated with supervisors and will have their history stored.</p>


<h4>Supervisor(s)</h4>
<p>Each user can be associated with a "supervisor". This is a way of linking a user to their educational supervisor to allow for supervisor reviewing of results. By default this just includes the supervisors email (and site) but if the superivsor wishes they can associate their account which allows (TODO) for on demand access.</p>


<h3>Cid Candidate(s)</h3>
<p>These are used when a person requires access to the test system for a one off purpose, for example a course. Ideally it should be avoided if a user has an account (see above) on the system.</p>

<p>The user will be given a candidate id (CID) and passcode that can be used to log into the system. This will allow them to take exams/packets and view results.</p>

<p>
The only required information is an email address.
</p>

<p>Although it is (currently) possible to link a cid user with a supervisor, this should be avoided as they should use a full account.<p>


<h2>Groups</h2>
<p>Groups are how users are given access to exams / packets.</p>
<p>2 types of groups can be created, they are essentially the same with one managing CID candidates, the other standard accounts</p>
<p>Once a group has been created this can be associated with a packet/exam/collection and the users contained within can be given access</p>


{% endblock %}

{% block js %}


{% comment %}     <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/bs4/dt-1.11.3/r-2.2.9/datatables.min.css"/>

    <script type="text/javascript" src="https://cdn.datatables.net/v/bs4/dt-1.11.3/r-2.2.9/datatables.min.js"></script> {% endcomment %}

    <script>
//        jQuery.fn.dataTable.render.ellipsis = function ( cutoff, wordbreak, escapeHtml ) {
            //var esc = function ( t ) {
                //return t
                    //.replace( /&/g, '&amp;' )
                    //.replace( /</g, '&lt;' )
                    //.replace( />/g, '&gt;' )
                    //.replace( /"/g, '&quot;' );
            //};

            //return function ( d, type, row ) {
                //// Order, search and type get the original data
                //if ( type !== 'display' ) {
                    //return d;
                //}

                //if ( typeof d !== 'number' && typeof d !== 'string' ) {
                    //return d;
                //}

                //d = d.toString(); // cast numbers

                //if ( d.length <= cutoff ) {
                    //return d;
                //}

                //var shortened = d.substr(0, cutoff-1);

                //// Find the last white space character in the string
                //if ( wordbreak ) {
                    //shortened = shortened.replace(/\s([^\s]*)$/, '');
                //}

                //// Protect against uncontrolled HTML input
                //if ( escapeHtml ) {
                    //shortened = esc( shortened );
                //}

                //return '<span class="ellipsis" title="'+esc(d)+'">'+shortened+'&#8230;</span>';
            //};
        //};

        function postAjax(data) {

            $.ajax({
                url: "{% url 'generic:manage_cid_users' %}",
                data: data,
                type: "POST",
                dataType: "json",
            })
            // $.ajax().done(), $.ajax().fail(), $ajax().always() are upto you. Add/change accordingly
                .done(function (data) {
                console.log(data);

                if (data.status == "success") {
                    toastr.info('Added/Updated');
                    location.reload();
                } else {
                    toastr.error(data.details)
                }
                // show some message according to the response.
                // For eg. A message box showing that the status has been changed
            })
                .always(function () {
                console.log('[Done]');
            })

        }

        function getGenericData() {
            selected_cids = []
            $("#manage-span tbody input:checked").each((n, el) => {
                selected_cids.push(parseInt(el.value));
            })
            return {
                csrfmiddlewaretoken: "{{ csrf_token }}",
                physics_exams: JSON.stringify($("#physics-exams").val()),
                rapid_exams: JSON.stringify($("#rapid-exams").val()),
                sba_exams: JSON.stringify($("#sbas-exams").val()),
                longs_exams: JSON.stringify($("#longs-exams").val()),
                anatomy_exams: JSON.stringify($("#anatomy-exams").val()),
                casecollection_exams: JSON.stringify($("#casecollection-exams").val()),
                cid_groups: JSON.stringify($("#cid-groups").val()),
                delete: false,
                emails: JSON.stringify(false),
                number_to_create: 0,
                activate: false,
                deactivate: false,
                add_exams: false,
                clear_exams: false,
                toggle_internal: false,
                selected_cids: JSON.stringify(selected_cids),
            }
        }

        $(document).ready(function () {

//            {% if exams %}
                //$("table").DataTable({
                    //columnDefs: [ {
                        //targets: [6,7,8,9,10],
                        //render: $.fn.dataTable.render.ellipsis( 17, true )
                    //} ],
                    //"paging": false,
                //});
            //{% else %}
                //$("table").DataTable({
                    //"paging": false,
                //});
            //{% endif %}

            $("#toggle-internal").click((evt) => {
                data = getGenericData();
                data["toggle_internal"] = true;
                postAjax(data);
            });
            $("#add-new-emails").click((evt) => {
                data = getGenericData();
                data["emails"] = JSON.stringify($("#emails-input").val());
                data["add_new_emails"] = true;
                postAjax(data);
            });
            $("#add-group").click((evt) => {
                data = getGenericData();
                data["add_group"] = true;
                postAjax(data);
            });
            $("#add-exams-selected-cids").click((evt) => {
                data = getGenericData();
                data["add_exams"] = true;
                postAjax(data);
            });
            $("#change-exams-selected-cids").click((evt) => {
                data = getGenericData();
                data["change_exams"] = true;
                postAjax(data);
            });
            $("#clear-exams-selected-cids").click((evt) => {
                data = getGenericData();
                data["clear_exams"] = true;
                postAjax(data);
            });
            $("#activate-selected-cids").click((evt) => {
                data = getGenericData();
                data["activate"] = true;
                postAjax(data);
            });
            $("#deactivate-selected-cids").click((evt) => {
                data = getGenericData();
                data["deactivate"] = true;
                postAjax(data);
            });
            $("#delete-selected-cids").click((evt) => {
                data = getGenericData();
                data["delete"] = true;
                postAjax(data);
            });

            $("#add-new-cids").click((evt) => {

                n = $("#add-number").get(0).value;

                if (n < 1) {
                    toastr.info("You need to enter how many users to add.");
                    return
                }

                data = getGenericData();
                data["number_to_create"] = n;

                postAjax(data);


            });
        });
    </script>
    <style>
        #cid-groups {
            margin: 20px;
        }
        .exam-selectors {
            display: flex;
        }

        .exam-selectors select {
            height: 200px;
        }
    </style>


{% endblock %}
