{% extends "layouts/base-electric.html" %}

{% load static %}

{% block title %} Source URLs | Importer {% endblock title %}

{% block stylesheets %}{% endblock stylesheets %}

{% block content %}

{% include "includes/navigation-transparent.html" %}

<div class="container-fluid">
    <div class="row row-gap-3">

        <div class="col">
            <div class="e-container-border e-container-radius">
                <div class="e-container e-container-radius p-2 pt-3 mb-3">
                    <h1 class="text-center">Source URLs</h1>

                    {% include "importer/partials/tabnavbar.html" %}

                    <h3>Complete Profiles/Galleries</h3>

                    <input type="text" class="form-control input-group-text my-2" onkeyup="filterTable('profiles', 0, this.value)" placeholder="Search for URLs...">

                    <div class="table-responsive">
                        <table id="profiles" class="table table-sm table-striped table-bordered table-responsive table-striped tabel-hover text-nowrap">
                            <thead>
                                <tr>
                                    <th>URL:<span class="ms-1 text-primary">↕</span></th>
                                    <th>Category:<span class="ms-1 text-primary">↕</span></th>
                                    <th>Added On:<span class="ms-1 text-primary">↕</span></th>
                                    <th data-bs-toggle="tooltip" title="Last Imported/Scaned">Imported:<span class="ms-1 text-primary">↕</span></th>
                                    {% if user.is_superuser or user.is_staff %}
                                    <th>Added By:<span class="ms-1 text-primary">↕</span></th>
                                    {% endif %}
                                    <th>Active:<span class="ms-1 text-primary">↕</span></th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for url in SourceURLs %}
                                {% if url.source_type == "C" %}
                                <tr id="C-{{ url.pk }}">
                                    <td>{{ url.url }}</td>
                                    <td>{{ url.category }}</td>
                                    <td data-timestamp="{{ url.date_added|date:'U' }}" data-bs-toggle="tooltip" title="{{ url.date_added|date:'Y-m-d H:i' }}">{{ url.date_added|date:'Y-m-d' }}</td>
                                    <td data-timestamp="{{ url.last_imported|date:'U' }}" data-bs-toggle="tooltip" title="{{ url.last_imported|date:'Y-m-d H:i' }}">{{ url.last_imported|date:'Y-m-d' }}</td>
                                    {% if user.is_superuser or user.is_staff %}
                                    <td>{{ url.added_by_user|capfirst }}</td>
                                    {% endif %}
                                    <td>{{ url.active }}</td>
                                </tr>
                                {% endif %}
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>

                    <hr class="my-3">

                    <h3>Single Posts</h3>

                    <input type="text" class="form-control input-group-text my-2" onkeyup="filterTable('posts', 0, this.value)" placeholder="Search for URLs...">

                    <table id="posts" class="table table-bordered table-responsive table-striped tabel-hover">
                        <thead>
                            <tr>
                                <th>URL:</th>
                                <th>Category:</th>
                                <th>Added On:</th>
                                <th>Last Imported/Scaned:</th>
                                {% if user.is_superuser or user.is_staff %}
                                <th>Added By</th>
                                {% endif %}
                                <th>Active</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for url in SourceURLs %}
                            {% if url.source_type == "P" %}
                            <tr>
                                <td>{{ url.url }}</td>
                                <td>{{ url.category }}</td>
                                <td>{{ url.date_added|date:'Y-m-d H:i' }}</td>
                                <td>{{ url.last_imported|date:'Y-m-d H:i' }}</td>
                                {% if user.is_superuser or user.is_staff %}
                                <td>{{ url.added_by_user|capfirst }}</td>
                                {% endif %}
                                <td>{{ url.active }}</td>
                            </tr>
                            {% endif %}
                            {% endfor %}
                        </tbody>
                    </table>

                </div>
            </div>
        </div>

    </div>
</div>

<script>
    function filterTable(tableId, columnIndex, input) {
        console.log(tableId, columnIndex, input.value);
        // Declare variables
        var filter = input.toUpperCase();
        var table = document.getElementById(tableId);
        var rows = table.getElementsByTagName("tr");
        
        // Loop through all table rows, and hide those who don't match the search query
        for (var i = 0; i < rows.length; i++) {
            var cells = rows[i].getElementsByTagName("td");
            if (cells.length) {
                var txtValue = cells[columnIndex].textContent || cells[columnIndex].innerText;
                if (txtValue.toUpperCase().indexOf(filter) > -1) {
                    rows[i].style.display = "";
                } else {
                    rows[i].style.display = "none";
                }
            }
        }
    }

    function sortTable(tableId, n) {
        var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
        table = document.getElementById(tableId);
        switching = true;
        // Set the sorting direction to ascending:
        dir = "asc";
        /* Make a loop that will continue until
        no switching has been done: */
        while (switching) {
            // Start by saying: no switching is done:
            switching = false;
            rows = table.rows;
            /* Loop through all table rows (except the
            first, which contains table headers): */
            for (i = 1; i < (rows.length - 1); i++) {
                // Start by saying there should be no switching:
                shouldSwitch = false;
                /* Get the two elements you want to compare,
                one from current row and one from the next: */
                x = rows[i].getElementsByTagName("TD")[n];
                y = rows[i + 1].getElementsByTagName("TD")[n];
                /* Check if the two rows should switch place,
                based on the direction, asc or desc: */
                if (dir == "asc") {
                    if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
                        // If so, mark as a switch and break the loop:
                        shouldSwitch = true;
                        break;
                    }
                } else if (dir == "desc") {
                    if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
                        // If so, mark as a switch and break the loop:
                        shouldSwitch = true;
                        break;
                    }
                }
            }
            if (shouldSwitch) {
                /* If a switch has been marked, make the switch
                and mark that a switch has been done: */
                rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
                switching = true;
                // Each time a switch is done, increase this count by 1:
                switchcount ++;
            } else {
                /* If no switching has been done AND the direction is "asc",
                set the direction to "desc" and run the while loop again. */
                if (switchcount == 0 && dir == "asc") {
                    dir = "desc";
                    switching = true;
                }
            }
        }
    }

    window.onload = function() {
        document.querySelectorAll('th').forEach((element) => { // Table headers
            element.addEventListener('click', function() {
                let table = this.closest('table');

                // If the column is sortable
                if (this.querySelector('span')) {
                    let order_icon = this.querySelector('span');
                    let order      = encodeURI(order_icon.innerHTML).includes('%E2%86%91') ? 'desc' : 'asc';
                    let separator  = '-----'; // Separate the value of it's index, so data keeps intact

                    let value_list = {}; // <tr> Object
                    let obj_key    = []; // Values of selected column

                    let string_count = 0;
                    let number_count = 0;

                    // <tbody> rows
                    table.querySelectorAll('tbody tr').forEach((line, index_line) => {
                        // Value of each field
                        let key = line.children[element.cellIndex].textContent.toUpperCase();

                        // Check if value is date, numeric or string
                        if (line.children[element.cellIndex].hasAttribute('data-timestamp')) {
                            // if value is date, we store it's timestamp, so we can sort like a number
                            key = line.children[element.cellIndex].getAttribute('data-timestamp');
                        }
                        else if (key.replace('-', '').match(/^[0-9,.]*$/g)) {
                            number_count++;
                        }
                        else {
                            string_count++;
                        }

                        value_list[key + separator + index_line] = line.outerHTML.replace(/(\t)|(\n)/g, ''); // Adding <tr> to object
                        obj_key.push(key + separator + index_line);
                    });
                    if (string_count === 0) { // If all values are numeric
                        console.log(obj_key);
                        obj_key.sort(function(a, b) {
                            return a.split(separator)[0] - b.split(separator)[0];
                        });
                        console.log(obj_key);
                    }
                    else {
                        console.log(obj_key);
                        obj_key.sort();
                        console.log(obj_key);
                    }

                    if (order === 'desc') {
                        console.log(obj_key);
                        obj_key.reverse();
                        console.log(obj_key);
                        order_icon.innerHTML = '&darr;';
                    }
                    else {
                        order_icon.innerHTML = '&uarr;';
                    }

                    let html = '';
                    obj_key.forEach(function(chave) {
                        html += value_list[chave];
                    });
                    table.getElementsByTagName('tbody')[0].innerHTML = html;
                }
            });
        });
    }
</script>

{% endblock content %}
