<% if @stats.nil? || @stats.empty? %>
<p class="genericNotice"><%= t('image_statistics.no_images') %></p>
<% else %>

<p>
    <ul>
        <li><%= t('image_statistics.total_devices', total_devices: @stats[:total_devices]) %></li>
        <li><%= t('image_statistics.image_count', image_count: @stats[:images].count) %></li>
    </ul>
</p>

<p><a href="#" id="download" class="btn"><%= t('image_statistics.download') %></a></p>

<fieldset>
    <legend><%= t('image_statistics.sorting') %></legend>
    <form autocomplete="off">
        <input type="radio" name="sort" id="sortByImage" checked><label for="sortByImage"><%= t('image_statistics.sort_by_image').html_safe %></label><br>
        <input type="radio" name="sort" id="sortByUsage"><label for="sortByUsage"><%= t('image_statistics.sort_by_usage') %></label>
    </form>
</fieldset>

<p><%= t('image_statistics.instructions') %></p>

<div id="output"></div>

<template id="template_imageStats">
    <table class="imageStats">
        <thead>
            <tr>
                <th><%= t('image_statistics.image_name_column').html_safe %></th>
                <th colspan="2" class="border"><%= t('image_statistics.usage_column') %></th>
            </tr>
        </thead>
        <tbody>
        </tbody>
    </table>
</template>

<template id="template_statsRow">
    <tr class="header">
        <td class="minimize-width">
            <span class="imageName"></span>
            <span class="releaseName"></span>
        </td>

        <td class="minimize-width border usage">XYZ</td>

        <td class="barCol">
            <div class="barOuter">
                <div class="barInner" style="">&nbsp;</div>
            </div>
        </td>
    </tr>

    <tr class="deviceListRow hidden">
        <td colspan="3">
            <ul></ul>
        </td>
    </tr>
</template>

<script>
// Raw statistics, generated server-side
const IMAGES = <%= raw JSON.pretty_generate(@stats[:images]) %>;

const SCHOOLS = <%= raw JSON.pretty_generate(@stats[:schools]) %>;

const collator = new Intl.Collator(
    // I guess this is a "neutral" sorting locale, because image names and
    // device hostnames don't have (should not have) anything outside of the
    // basic 7-bit ASCII
    "en-US", {
        usage: "sort",
        sensitivity: "accent",
        ignorePunctuation: true,
        numeric: true,
    }
);

const formatter = Intl.NumberFormat("<%= supertable_sorting_locale %>", { style: "percent", minimumFractionDigits: 1 });

// Copy-pasted from assets/javascripts/common/dom.js. Can't import it because
// we're not in a module. Grrr.
function getTemplate(id)
{
    return document.querySelector(`template#template_${id}`).content.cloneNode(true);
}

function buildTable(images)
{
    const totalDevices = <%= @stats[:total_devices] %>;

    const table = getTemplate("imageStats"),
          tbody = table.querySelector("tbody");

    for (const imageName of images) {
        const image = IMAGES[imageName];
        const row = getTemplate("statsRow");

        // Decide how to colorize this row, based on the image name
        let cls = "other";

        if (imageName.includes("stretch"))
            cls = "stretch";
        else if (imageName.includes("buster"))
            cls = "buster";
        else if (imageName.includes("bullseye"))
            cls = "bullseye";
        else if (imageName.includes("bookworm"))
            cls = "bookworm";

        const imageSpan = row.querySelector("span.imageName"),
              releaseSpan = row.querySelector("span.releaseName");

        // Image filename
        imageSpan.classList.add(`release-${cls}`);
        imageSpan.innerText = imageName;

        // Known release names
        if (image.release !== null)
            releaseSpan.innerText = image.release;
        else releaseSpan.remove();

        // Bar graph
        const fraction = image.devices.length / totalDevices;

        row.querySelector("td.usage").innerText = `${image.devices.length}/${totalDevices} (${formatter.format(fraction)})`;
        row.querySelector("div.barInner").style.width = `${fraction * 100.0}%`;

        // List all devices using this image
        const list = row.querySelector("tr.deviceListRow ul");

        for (const device of image.devices.sort((a, b) => collator.compare(a.name, b.name))) {
            const school = SCHOOLS[device.school];
            const li = document.createElement("li");

            <% if show_school_links %>
            li.innerHTML = `<a href="${device.link}">${device.name}</a> (<a href="${school.link}">${school.name}</a>)`;
            <% else %>
            li.innerHTML = `<a href="${device.link}">${device.name}</a> (${school.name})`;
            <% end %>
            list.appendChild(li);
        }

        // Setup collapsible header events
        row.querySelector("tr.header").addEventListener("click", e => e.target.closest("tr").nextElementSibling.classList.toggle("hidden"));

        tbody.appendChild(row);
    }

    const output = document.getElementById("output");

    output.innerText = null;
    output.appendChild(table);
}

function sortByUsage(raw)
{
    // Simply sort the images by their usage count
    let images = [];

    for (const image of Object.keys(raw))
        images.push([image, raw[image].devices.length]);

    return images.sort(function(a, b) {
        if (a[1] == b[1]) {
            // compare image names to resolve the tie (and stabilize the sort a bit)
            return collator.compare(a[0], b[0]);
        }

        return b[1] - a[1];
    }).map(i => i[0]);          // reduce to 1D array
}

function sortByImage(raw)
{
    // Split into multiple arrays based on the image name, sort them separately
    // and finally concatenate
    function sortImages(what)
    {
        return what.sort(function(a, b) {
            return collator.compare(a, b) * -1;     // -1 = reverse the order
        });
    }

    let bookworm = [],
        bullseye = [],
        buster = [],
        stretch = [],
        other = [];

    for (const image of Object.keys(raw)) {
        if (image.indexOf("bookworm") != -1)
            bookworm.push(image);
        else if (image.indexOf("bullseye") != -1)
            bullseye.push(image);
        else if (image.indexOf("buster") != -1)
            buster.push(image);
        else if (image.indexOf("stretch") != -1)
            stretch.push(image);
        else other.push(image);
    }

    bookworm = sortImages(bookworm);
    bullseye = sortImages(bullseye);
    buster = sortImages(buster);
    stretch = sortImages(stretch);
    other = sortImages(other);

    return [].concat(bookworm, bullseye, buster, stretch, other);
}

function download()
{
    const timestamp = I18n.strftime(new Date(), "%Y-%m-%d-%H-%M-%S")

    const data = {
        schools: SCHOOLS,
        images: IMAGES,
    };

    const b = new Blob([JSON.stringify(data, null, "  ")], { type: "text/json" });

    const  a = window.document.createElement("a");

    a.href = window.URL.createObjectURL(b);
    a.download = `<%= LdapOrganisation.current.o %>-images-${timestamp}.json`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
}

// Initial update
buildTable(sortByImage(IMAGES));

// Setup events
document.getElementById("sortByImage").addEventListener("click", () => buildTable(sortByImage(IMAGES)));
document.getElementById("sortByUsage").addEventListener("click", () => buildTable(sortByUsage(IMAGES)));
document.getElementById("download").addEventListener("click", () => download());
</script>

<% end %>
