/**
 * BFH Science Self-Service Portal
 * Copyright (C) 2025-2026 IKUS Software
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses />.
 */

/**
 * Custom button to open bootstrap modal.
 */
$(document).ready(function() {

    const textDisplay = $.fn.dataTable.render.text().display;

    $.fn.dataTable.ext.buttons.sspPdf = {
        extend: 'pdf',
        customize: function(pdfDoc, config, dt) {
            // Adjust margins & add footer to PDF.
            Object.assign(pdfDoc, {
                'pageMargins': [40, 40, 40, 40],
                'header': {
                    columns: [
                        {text: document.title },
                        {text: window.location.href, alignment: 'right'}
                    ],
                    margin: [40, 10, 40, 0],
                },
                'footer': {
                    columns: [
                        {text: config.description },
                        {text: config.filename + config.extension, alignment: 'right'}
                    ],
                    margin: [40, 10, 40, 0],
                }
            });
        }
    };
   
    $.fn.dataTable.ext.buttons.sspShowModal = {
        text: 'Open Modal',
        className: 'ssp-show-modal',
        action: function(e, dt, node, config) {
            const modal = new bootstrap.Modal(document.querySelector(config.target));
            modal.show();
        }
    };

    $.fn.dataTable.render.sspCopyButton = function() {
        return {
            display: function(data, type, row, meta) {
                /* Make data safe */
                const escapeData = textDisplay(data);
                if (data) {
                    return `<span class="ssp-hover-zone"><button class="btn btn-sm btn-outline-secondary btn-clipboard ssp-hover-show" data-clipboard-text="${escapeData}"><i class="bi bi-clipboard" aria-hidden="true"></i></button> ${escapeData}</span>`
                } else {
                    return '';
                }
            },
        };
    }

    $.fn.dataTable.render.sspManageStorageButton = function() {
        return {
            display: function(data, type, row, meta) {
                const api = new $.fn.dataTable.Api(meta.settings);
                if(row.manage_url) {
                    /* Show manage button when manage_url is provided */
                    const manageLabel = textDisplay(api.settings().i18n('ssp.manage'));
                    const manageUrl = textDisplay(row.manage_url);
                    return `<a class="btn btn-sm btn-primary btn-hover text-nowrap ssp-external" target="_blank" href="${manageUrl}" rel="noopener noreferrer">${manageLabel}</a>`;
                } else if (row.group) {
                    /* Show "Change access" when group name is provided */
                    const storageName = textDisplay(row.name);
                    const changeLabel =  textDisplay(api.settings().i18n('ssp.change'));
                    return `<a class="btn btn-sm btn-primary btn-hover text-nowrap" data-bs-toggle="modal" data-bs-target="#modal-request-storage-access-change" data-storage-name="${storageName}">${changeLabel}</a>`;              
                }
                return '';
            },
        };
    }

    $.fn.dataTable.render.sspManageButton = function() {
        return {
            display: function(data, type, row, meta) {
                /* Show manage button when manage_url is provided */
                const api = new $.fn.dataTable.Api(meta.settings);
                if(row.manage_url) {
                    const manageLabel = textDisplay(api.settings().i18n('ssp.manage'));
                    const manageUrl = textDisplay(row.manage_url);
                    return `<a class="btn btn-sm btn-primary btn-hover text-nowrap ssp-external" target="_blank" href="${manageUrl}" rel="noopener noreferrer">${manageLabel}</a>`;
                }
                return '';
            },
        };
    }

    /*
    * Cloud project row grouping.
    */
    $.fn.dataTable.rowGroupRender.sspProject = function () {

        function tooltipFactory(icon, label, units, used, quota) {
            const pctUsed = quota > 0 ? Math.min(100, Math.round((used / quota) * 100)) : 0;

            const htmlTooltip = `<div class="text-start">
            <strong>${label} Quota</strong>
            <div class="progress">
                <div class="progress-bar" role="progressbar" style="width:${pctUsed}%;" aria-valuenow="${pctUsed}" aria-valuemin="0" aria-valuemax="100">${pctUsed}%</div>
            </div>
            Used: ${used} ${units}<br/>
            Quota: ${quota} ${units}<br/><br/>
            Remaining: ${Math.max(0, quota - used)} ${units}
            </div>
            `;
            return $(`<span class="ms-2 ssp-quota-value" data-bs-toggle="tooltip" data-bs-html="true" data-bs-placement="bottom"><i class="bi ${icon}" aria-hidden="true"></i> ${used} / ${quota} ${units}</span>`)
            .attr('title', htmlTooltip)
        }

        return function (rows, group) {
            // Compute some values
            const project = rows.data()[0].project;
            const cpuUsed = rows.data().toArray().reduce((sum, row) => sum + (Number(row.cpu) || 0), 0);
            const ramUsed = rows.data().toArray().reduce((sum, row) => sum + (Number(row.ram) || 0), 0);
            const diskUsed = rows.data().toArray().reduce((sum, row) => sum + (Number(row.disk) || 0), 0);

            const $container = $('<div class="d-flex justify-content-between align-items-center"></div>');
            $('<span/>').text(`Project ${project.name}`).appendTo($container);

            const $right = $('<div class="fw-normal"></div>');
            $right
            .append(tooltipFactory('bi-cpu', 'CPU', 'cores', cpuUsed,  project.cpu))
            .append(tooltipFactory('bi-memory', 'Memory', 'GiB',  ramUsed,  project.ram))
            .append(tooltipFactory('bi-hdd', 'Storage', 'GiB', diskUsed, project.disk));

            $container.append($right);
            return $container; // RowGroup accepts string, DOM node, or jQuery object
        };
    };
    /*
     * Cloud quota.
     */
    $.fn.dataTable.render.sspQuota = function() {
        return {
            display: function(data, type, row, meta) {
                const cpu = textDisplay(row.cpu);
                const ram = textDisplay(row.ram);
                const disk = textDisplay(row.disk);
                const html = `
                    <span class="ms-2 ssp-quota-value" data-bs-toggle="tooltip" data-bs-html="true" data-bs-placement="bottom"><i class="bi bi-cpu" aria-hidden="true"></i> ${cpu} cores</span>
                    <span class="ms-2 ssp-quota-value" data-bs-toggle="tooltip" data-bs-html="true" data-bs-placement="bottom"><i class="bi bi-memory" aria-hidden="true"></i> ${ram} GiB</span>
                    <span class="ms-2 ssp-quota-value" data-bs-toggle="tooltip" data-bs-html="true" data-bs-placement="bottom"><i class="bi bi-hdd" aria-hidden="true"></i> ${disk} GiB</span>
                `;
                return html
            },
        };
    }
    /*
     * Owner(s) linkt with mailto or user's details.
     */
    $.fn.dataTable.render.sspOwners = function(mailto) {
        return {
            display: function(data, type, row, meta) {
                // Safety check
                if (!Array.isArray(data) || data.length === 0) {
                    return '';
                }
                const api = new $.fn.dataTable.Api(meta.settings);
                const subject = encodeURIComponent(api.settings().i18n('ssp.mailtoSubject'));
                return data
                    .toSorted(function (a, b) {
                        const nameA = (a.name ?? '').toLowerCase();
                        const nameB = (b.name ?? '').toLowerCase();
                        return nameA.localeCompare(nameB);
                    })
                    .map(function (owner) {
                        const escapeEmail = encodeURIComponent(owner.email ?? '');
                        const escapeName= textDisplay(owner.name ?? '');
                        const escapeUsername = textDisplay(owner.username ?? '');
                        // Build URL.
                        let href=`/dashboard/?u=${escapeUsername}`;
                        if (mailto) {
                            if(owner.email) {
                                href = `mailto:${escapeEmail}?subject=${subject}`;
                            } else {
                                href = "#";
                            }
                        }
                        return `<a class="text-nowrap" href="${href}">${escapeName} [${escapeUsername}]</a>`;
                    })
                    .filter(Boolean)
                    .join('<br/>');
            }
        };
    }
});
