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

{% load crispy_forms_tags %}
{% load render_table from django_tables2 %}
{% block content_container_class %}container-fluid content-wide px-3{% endblock %}
{% block css %}
{% endblock %}

{% block content %}

    <div class="d-flex justify-content-between align-items-center mb-3">
        <h2 class="mb-0">Manage Candidates</h2>
        <a href="{% url 'generic:import_exam_answers' %}" class="btn btn-primary btn-sm">
            <i class="bi bi-upload me-1"></i> Import Exam Answers
        </a>
    </div>

    <div>
        <span id="manage-span">
            {% render_table table %}
        </span>
    </div>
    {% include "generic/partials/filter_bar.html" with filter=filter app_name=app_name collapse_id="bottom-filter-body" %}

    <details>
        <summary>
            <h3>Add/Edit CID users</h3>
        </summary>
        <div>
            Groups<br />
            <select id="cid-groups">
                <option value="">----</option>
                {% for name, id in cid_user_groups %}
                    <option value="{{id}}">{{name}}</option>
                {% endfor %}

            </select>
        </div>
        <h4>Edit existing users</h4>
        <p>Users can be edited using the below buttons once they have been selected in the table. If you need to add a group to a user(s) select it above. Once a CID user is part of a group they can be added to exams via the exam candidate page.</p>
        <button id="activate-selected-cids">Activate selected</button>
        <button id="deactivate-selected-cids">Deactivate selected</button>
        <button id="delete-selected-cids">Delete selected</button>
        <button id="toggle-internal">Toggle internal</button>
        <button id="add-group">Add Group to users</button>
        <h4>Create New Users</h4>
        <p>New CID users can be created by the two below buttons. If you want to create blank users you can specify the number in the associated box and click the relevant button. If you have a list of email addresses you can enter them in the relevant box and click "Add New Users From Email" and a new user will be created for each user (you do not need to specify the number of users). Ideally you will have already created a <a href="{% url 'generic:cid_group_view' %}">CID user group</a> that you can add to the newly generated users using the above select box.</p>
        <button id="add-new-cids" title="This will create N new users">Add New (Blank) Users</button>
        <input type="number" id="add-number" value="number to add" placeholder="Number of new users"><br />
        <p>or</p>
        <button id="add-new-emails" title="This will create users from a list of email addresses">Add New Users From Email</button>
        <textarea id="emails-input" name="emails" rows="4" cols="50" placeholder="Enter emails here (single email per line)"></textarea>

        <details>
            <summary>Edit CID exams</summary>
            <p>This should be done via the exams pages one via group management.</p>
            <p>Select exams below to add user(s) to (or edit existing user(s)).</p>
            <div class="exam-selectors">
                <span>
                    Physics Exams<br />
                    <select id="physics-exams" multiple="multiple">
                        {% for name, id in physics_exams %}
                            <option value="{{id}}">{{name}}</option>
                        {% endfor %}

                    </select>
                </span>
                <span>
                    Rapid Exams<br />
                    <select id="rapid-exams" multiple="multiple">
                        {% for name, id in rapid_exams %}
                            <option value="{{id}}">{{name}}</option>
                        {% endfor %}

                    </select>
                </span>
                <span>
                    Sba Exams<br />
                    <select id="sbas-exams" multiple="multiple">
                        {% for name, id in sba_exams %}
                            <option value="{{id}}">{{name}}</option>
                        {% endfor %}

                    </select>
                </span>
                <span>
                    Long Exams<br />
                    <select id="longs-exams" multiple="multiple">
                        {% for name, id in longs_exams %}
                            <option value="{{id}}">{{name}}</option>
                        {% endfor %}

                    </select>
                </span>
                <span>
                    Anatomy Exams<br />
                    <select id="anatomy-exams" multiple="multiple">
                        {% for name, id in anatomy_exams %}
                            <option value="{{id}}">{{name}}</option>
                        {% endfor %}

                    </select>
                </span>
                <span>
                    Shorts Exams<br />
                    <select id="shorts-exams" multiple="multiple">
                        {% for name, id in shorts_exams %}
                            <option value="{{id}}">{{name}}</option>
                        {% endfor %}

                    </select>
                </span>
                <span>
                    CaseCollection Exams<br />
                    <select id="casecollection-exams" multiple="multiple">
                        {% for name, id in casecollection_exams %}
                            <option value="{{id}}">{{name}}</option>
                        {% endfor %}

                    </select>
                </span>


            </div>
            <button id="add-exams-selected-cids">Add selected exams</button>
            <button id="change-exams-selected-cids">Change selected exams</button>
            <button id="clear-exams-selected-cids">Clear selected exams</button>

        </details>
    </details>

{% 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()),
                shorts_exams: JSON.stringify($("#shorts-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 %}
