// This file is part of Moodle - http://moodle.org/
//
// Moodle 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.
//
// Moodle 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 Moodle.  If not, see <http://www.gnu.org/licenses/>.

/**
 * dataTables_init.js
 *
 * @package   local_kopere_dashboard
 * @copyright 2026 Eduardo Kraus {@link https://eduardokraus.com}
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

define([
    "jquery",
    "local_kopere_dashboard/dataTables",
    "local_kopere_dashboard/dataTables.buttons",
    "local_kopere_dashboard/dataTables.buttons.html5",
    "local_kopere_dashboard/dataTables.buttons.print",
    "local_kopere_dashboard/jszip",
], function ($) {
    let dataTables_init = {
        init: function (tableid, params) {
            if (!params) {
                let params_json = $(`#tableparams_${tableid}`).val();
                params = JSON.parse(params_json);
            }

            let renderer = {
                mustacheRenderer: function (data, type, row, info) {
                    if (type == "sort") {
                        let d = data.replace(/<[^>]*>/g, '');
                        if (/^\d/.test(data)) {
                            d = d.split(",").join(".");
                            d = parseFloat(d);

                            return d;
                        }
                        return d;

                    } else if (type != 'display') {
                        return data;
                    }

                    let columns = info.settings.aoColumns;
                    let col = info.col;
                    let column = columns[col];
                    let columnname = column.data;

                    if (row[`${columnname}_mustache`]) {
                        return row[`${columnname}_mustache`];
                    } else {
                        return data;
                    }
                },
                numberRenderer: function (data, type) {
                    if (type == "sort") {
                        if (/^\d/.test(data)) {
                            data = data.split(",").join(".");
                            data = parseFloat(data);

                            return data;
                        }
                        return data;
                    }
                    if (data === null) {
                        return "";
                    }
                    if (type != 'display') {
                        return data;
                    }

                    data = dataTables_init.numberFormat(data, 2);

                    return '<div class="text-center text-nowrap">' + data + '</div>';
                },
                currencyRenderer: function (data, type) {
                    if (type != 'display') {
                        return data;
                    }

                    return `<div class="text-center text-nowrap">R$ ${data}</div>`;
                },
                filesizeRenderer: function (data, type) {
                    if (type != 'display') {
                        return data;
                    }

                    if (data == null || data < 1) {
                        return '0 b';
                    } else if (data < 1000) {
                        return data + ' b';
                    } else if (data < 1000 * 1000) {
                        data = data / (1000);
                        return data.toFixed(2) + ' Kb';
                    } else if (data < 1000 * 1000 * 1000) {
                        data = data / (1000 * 1000);
                        return data.toFixed(2) + ' Mb';
                    } else if (data < 1000 * 1000 * 1000 * 1000) {
                        data = data / (1000 * 1000 * 1000);
                        return data.toFixed(2) + ' Gb';
                    } else {
                        return data.toFixed(2) + ' Tb';
                    }
                },
                dateRenderer: function (data, type) {
                    if (type != 'display') {
                        return data;
                    }

                    if (data < 1000) {
                        return "";
                    }

                    function twoDigit($value) {
                        if ($value < 10) {
                            return '0' + $value;
                        }
                        return $value;
                    }

                    let a = new Date(data * 1000);
                    let year = a.getFullYear();
                    let month = twoDigit(a.getMonth() + 1);
                    let day = twoDigit(a.getDate());

                    if (M.cfg.language == "en") {
                        return `<div class="text-nowrap">${month}/${day}/${year}</div>`;
                    } else {
                        return `<div class="text-nowrap">${day}/${month}/${year}</div>`;
                    }
                },
                datetimeRenderer: function (data, type) {
                    if (type != 'display') {
                        return data;
                    }

                    if (data < 1000) {
                        return "";
                    }

                    function twoDigit($value) {
                        if ($value < 10) {
                            return '0' + $value;
                        }
                        return $value;
                    }

                    let a = new Date(data * 1000);
                    let year = a.getFullYear();
                    let month = twoDigit(a.getMonth() + 1);
                    let day = twoDigit(a.getDate());
                    let hour = twoDigit(a.getHours());
                    let min = twoDigit(a.getMinutes());

                    if (M.cfg.language == "en") {
                        return `<div class="text-nowrap">${month}/${day}/${year} ${hour}:${min}</div>`;
                    } else {
                        return `<div class="text-nowrap">${day}/${month}/${year} ${hour}:${min}</div>`;
                    }
                },
                visibleRenderer: function (data, type) {
                    if (type != 'display') {
                        if (type == 'filter') {
                            if (!data) {
                                return M.util.get_string('invisible', "local_kopere_dashboard");
                            } else {
                                return M.util.get_string('visible', "local_kopere_dashboard");
                            }
                        }
                        return data;
                    }

                    if (!data) {
                        return '<div class="status-pill grey"  title="' +
                            M.util.get_string('invisible', "local_kopere_dashboard") +
                            '"></div>';
                    } else {
                        return '<div class="status-pill green" title="' + M.util.get_string('visible', "local_kopere_dashboard") +
                            '"></div>';
                    }
                },
                statusRenderer: function (data, type) {
                    if (type != 'display') {
                        if (type == 'filter') {
                            if (data) {
                                return M.util.get_string('inactive', "local_kopere_dashboard");
                            } else {
                                return M.util.get_string('active', "local_kopere_dashboard");
                            }
                        }
                        return data;
                    }

                    if (data) {
                        return '<div class="status-pill grey"  title="' +
                            M.util.get_string('inactive', "local_kopere_dashboard") +
                            '"></div>';
                    } else {
                        return '<div class="status-pill green" title="' +
                            M.util.get_string('active', "local_kopere_dashboard") +
                            '"></div>';
                    }
                },
                deletedRenderer: function (data, type) {
                    if (type != 'display') {
                        if (type == 'filter') {
                            if (!data) {
                                return M.util.get_string('notification_status_deleted', "local_kopere_dashboard");
                            } else {
                                return M.util.get_string('active', "local_kopere_dashboard");
                            }
                        }
                        return data;
                    }

                    if (!data) {
                        return `<div class="status-pill grey"
                                     title="${M.util.get_string('notification_status_deleted', "local_kopere_dashboard")}"></div>`;
                    } else {
                        return `<div class="status-pill green"
                                     title="${M.util.get_string('active', "local_kopere_dashboard")}"></div>`;
                    }
                },
                trueFalseRenderer: function (data, type) {
                    if (type != 'display') {
                        return data;
                    }

                    if (data == 0 || data == false || data == 'false') {
                        return M.util.get_string('no');
                    } else {
                        return M.util.get_string('yes');
                    }
                },
                userphotoRenderer: function (data, type) {
                    if (type != 'display') {
                        return data;
                    }

                    return `<img class="media-object"
                                 src="${M.cfg.wwwroot}/local/kopere_dashboard/profile-image.php?type=photo_user&id=${data}"
                                 style="width:35px;height:35px" />`;
                },
                secondsRenderer: function (data, type) {
                    if (type != 'display') {
                        return data;
                    }

                    let tempo = parseInt(data);
                    if (isNaN(tempo) || tempo < 1) {
                        return '00:00:00';
                    }

                    let min = parseInt(tempo / 60);
                    let hor = parseInt(min / 60);

                    min = min % 60;
                    if (min < 10) {
                        min = "0" + min;
                        min = min.substr(0, 2);
                    }

                    let seg = tempo % 60;
                    if (seg <= 9) {
                        seg = "0" + seg;
                    }

                    if (hor <= 9) {
                        hor = "0" + hor;
                    }

                    return `${hor}:${min}:${seg}`;
                },
                timeRenderer: function (data, type) {
                    if (type != 'display') {
                        return data;
                    }

                    let tempo = parseInt(data);
                    if (isNaN(tempo) || tempo < 1) {
                        return '00:00:00';
                    }

                    let min = parseInt(tempo / 60);
                    let hor = parseInt(min / 60);

                    min = min % 60;
                    if (min < 10) {
                        min = "0" + min;
                        min = min.substr(0, 2);
                    }

                    let seg = tempo % 60;
                    if (seg <= 9) {
                        seg = "0" + seg;
                    }

                    if (hor <= 9) {
                        hor = "0" + hor;
                    }

                    return `${hor}:${min}:${seg}`;
                },
            };

            let newColumnDefs = [];
            let iterate = $.each(params.columnDefs, function (id, columnDef) {
                switch (columnDef.render) {
                    case "numberRenderer":
                        columnDef.render = renderer.numberRenderer;
                        break;
                    case "currencyRenderer":
                        columnDef.render = renderer.currencyRenderer;
                        break;
                    case "filesizeRenderer":
                        columnDef.render = renderer.filesizeRenderer;
                        break;
                    case "dateRenderer":
                        columnDef.render = renderer.dateRenderer;
                        break;
                    case "datetimeRenderer":
                        columnDef.render = renderer.datetimeRenderer;
                        break;
                    case "visibleRenderer":
                        columnDef.render = renderer.visibleRenderer;
                        break;
                    case "statusRenderer":
                        columnDef.render = renderer.statusRenderer;
                        break;
                    case "deletedRenderer":
                        columnDef.render = renderer.deletedRenderer;
                        break;
                    case "trueFalseRenderer":
                        columnDef.render = renderer.trueFalseRenderer;
                        break;
                    case "userphotoRenderer":
                        columnDef.render = renderer.userphotoRenderer;
                        break;
                    case "secondsRenderer":
                        columnDef.render = renderer.secondsRenderer;
                        break;
                    case "timeRenderer":
                        columnDef.render = renderer.timeRenderer;
                        break;

                    default:
                        columnDef.render = renderer.mustacheRenderer;
                        break;
                }
                newColumnDefs.push(columnDef);
            });
            $.when(iterate).done(function () {
                params.columnDefs = newColumnDefs;
                params.oLanguage = {
                    sEmptyTable: M.util.get_string('datatables_sEmptyTable', "local_kopere_dashboard"),
                    sInfo: M.util.get_string('datatables_sInfo', "local_kopere_dashboard"),
                    sInfoEmpty: M.util.get_string('datatables_sInfoEmpty', "local_kopere_dashboard"),
                    sInfoFiltered: M.util.get_string('datatables_sInfoFiltered', "local_kopere_dashboard"),
                    sInfoPostFix: M.util.get_string('datatables_sInfoPostFix', "local_kopere_dashboard"),
                    sInfoThousands: M.util.get_string('datatables_sInfoThousands', "local_kopere_dashboard"),
                    sLengthMenu: M.util.get_string('datatables_sLengthMenu', "local_kopere_dashboard"),
                    sLoadingRecords: M.util.get_string('datatables_sLoadingRecords', "local_kopere_dashboard"),
                    sProcessing: M.util.get_string('datatables_sProcessing', "local_kopere_dashboard"),
                    sErrorMessage: M.util.get_string('datatables_sErrorMessage', "local_kopere_dashboard"),
                    sZeroRecords: M.util.get_string('datatables_sZeroRecords', "local_kopere_dashboard"),
                    sSearch: "",
                    sSearchPlaceholder: M.util.get_string('datatables_sSearch', "local_kopere_dashboard"),
                    buttons: {
                        print_text: M.util.get_string('datatables_buttons_print_text', "local_kopere_dashboard"),
                        copy_text: M.util.get_string('datatables_buttons_copy_text', "local_kopere_dashboard"),
                        csv_text: M.util.get_string('datatables_buttons_csv_text', "local_kopere_dashboard"),
                        copySuccess1: M.util.get_string('datatables_buttons_copySuccess1', "local_kopere_dashboard"),
                        copySuccess_: M.util.get_string('datatables_buttons_copySuccess_', "local_kopere_dashboard"),
                        copyTitle: M.util.get_string('datatables_buttons_copyTitle', "local_kopere_dashboard"),
                        copyKeys: M.util.get_string('datatables_buttons_copyKeys', "local_kopere_dashboard"),
                        pageLength: {
                            '_': M.util.get_string('datatables_buttons_pageLength_', "local_kopere_dashboard"),
                            '-1': M.util.get_string('datatables_buttons_pageLength_1', "local_kopere_dashboard"),
                        }
                    },
                    select: {
                        rows: {
                            _: M.util.get_string('datatables_buttons_select_rows_', "local_kopere_dashboard"),
                            0: "",
                            1: M.util.get_string('datatables_buttons_select_rows1', "local_kopere_dashboard"),
                        }
                    },
                    oAria: {
                        sSortAscending: M.util.get_string('datatables_oAria_sSortAscending', "local_kopere_dashboard"),
                        sSortDescending: M.util.get_string('datatables_oAria_sSortDescending', "local_kopere_dashboard"),
                        paginate: {
                            next: M.util.get_string('datatables_oPaginate_sNext', "local_kopere_dashboard"),
                            previous: M.util.get_string('datatables_oPaginate_sPrevious', "local_kopere_dashboard"),
                            first: M.util.get_string('datatables_oPaginate_sFirst', "local_kopere_dashboard"),
                            last: M.util.get_string('datatables_oPaginate_sLast', "local_kopere_dashboard"),
                        },
                    }
                };
                params.responsive = true;
                params.locale = M.cfg.language;

                if (params.export_title) {
                    params.buttons = [
                        'pageLength',
                        {
                            extend: 'print',
                            text: M.util.get_string('datatables_buttons_print_text', "local_kopere_dashboard"),
                            title: params.export_title
                        }, {
                            extend: 'pdf',
                            text: "PDF",
                            title: params.export_title
                        }, {
                            extend: 'excel',
                            text: 'Excel',
                            title: params.export_title
                        }, {
                            extend: 'csv',
                            text: M.util.get_string('datatables_buttons_csv_text', "local_kopere_dashboard"),
                            title: params.export_title
                        }, {
                            extend: 'copy',
                            text: "Copy",
                            title: params.export_title
                        },
                    ];
                    params.dom = 'frtipB';
                    params.select = true;
                }

                let count_error = 0;
                $.fn.dataTable.ext.errMode = function () {
                    if (count_error < 20) {
                        let _processing = $("#" + tableid + "_processing");
                        setTimeout(function () {
                            _processing.show().html(
                                "<div style='color:#e91e63'>" +
                                M.util.get_string('datatables_sErrorMessage', "local_kopere_dashboard", "<span class='counter'>30</span>") +
                                "</div>");
                        }, 500);

                        let timer = 30;
                        let _inteval = setInterval(function () {
                            if (--timer <= 0) {
                                _processing.html(M.util.get_string('datatables_sProcessing', "local_kopere_dashboard"));
                                clearInterval(_inteval);
                                window[tableid].ajax.reload();
                            }
                            _processing.find(".counter").html(timer);
                        }, 1000);
                    }
                    count_error++;
                };

                let preDrawCallback_complete = false;
                params.preDrawCallback = function () {
                    console.log("preDrawCallback");
                    if (preDrawCallback_complete) return;
                    preDrawCallback_complete = true;

                    const $wrapper = $(`#${tableid}_wrapper`);
                    const $search = $wrapper.find('> .dt-search');
                    const $controls = $wrapper
                        .prev('.block-heading')
                        .find('> .block-controls');

                    if ($search.length && $controls.length) {
                        $search.addClass("simplesearchform").css({
                            "margin-top": "-2px",
                            "margin-right": "24px",
                        });
                        $search.appendTo($controls);
                    }

                    $(`#${tableid}`).wrap('<div class="table-responsive"></div>');

                    const $paging = $wrapper.find(".dt-paging");
                    const $buttons = $wrapper.find(".dt-buttons");
                    const $newDiv = $("<div>", {class: "dt-area-buttons"});
                    $newDiv.insertBefore($paging);
                    $newDiv.append($paging);
                    $newDiv.append($buttons);
                };

                params.infoCallback = function (settings, start, end) {
                    console.log([settings, start, end]);
                    // if (end) {
                    //     $("#" + tableid + "_wrapper .group-controls").show(200);
                    // } else {
                    //     $("#" + tableid + "_wrapper .group-controls").hide(200);
                    // }
                };

                window[tableid] = $("#" + tableid).DataTable(params);
            });
        },

        numberFormat: function (number, decimals) {
            let options = {
                minimumFractionDigits: decimals,
                maximumFractionDigits: decimals
            };
            return number.toLocaleString(M.cfg.language, options);
        },

        click: function (tableid, clickchave, clickurl) {
            $('#' + tableid + ' tbody').on('click', 'tr', function () {
                let data = window[tableid].row(this).data();
                dataTables_init._click_internal(data, clickchave, clickurl)
            });
        },

        _click_internal: function (data, clickchave, clickurl) {
            let iterate1 = $.each(clickchave, function (id, chave) {
                clickurl = clickurl.replace('{' + chave + '}', data[chave]);
                clickurl = clickurl.replace('%7B' + chave + '%7D', data[chave]);
            });

            $.when(iterate1).done(function () {
                location.href = clickurl;
            });
        }
    };

    return dataTables_init;
});
