const filterTableId = "#filterTable";
const filterModalId = "#filterFormModal";


// region Init Module

function initFiltersModule() {
    initializeDataTable(
        filterTableId,
        [
            {
                title: "Name",
                data: "name",
                className: "col-name",
                render: renderEditColumn
            },
            {
                title: "Match",
                data: "match",
                className: "col-name"
            },
            {
                title: "Algorithm",
                data: "matching_algorithm",
                className: "col-date",
                render: function(data) {
                    switch (data) {
                        case 1: return "Any Word";
                        case 2: return "All Words";
                        case 3: return "Exact Match";
                        case 4: return "Regular Expression";
                        case 5: return "Fuzzy Match";
                        default:
                            console.error(`unknown matching algorithm '${data}'`);
                            return data;
                    }

                }
            },
            {
                title: "Case-Sensitive",
                data: "is_insensitive",
                className: "col-date text-center",
                render: data => renderBooleanColumn(!data)
            },
            {
                title: "Type",
                data: "is_whitelist",
                className: "col-date",
                render: data => data ? "Only Allow" : "Reject All"
            }
        ]
    )
}


// region Load Data

$(document).on("selectedServerChange", async function() {
    await loadFilterData();
});

$(filterTableId).on("doDataLoad", async function() {
    await loadFilterData();
});

async function loadFilterData() {
    if (!selectedServer) {
        return;
    }

    setTableFilter(filterTableId, "server", selectedServer.id);
    await loadTableData(filterTableId, "/api/filters/", "GET");
}

// region Table Share Btn

// getTableFiltersComponent(filterTableId).filter(".js-tableShareBtn").on("click", async () => {
//     createModal({
//         title: "Share"
//     })
// });

// region Table Delete Btns

$(filterModalId).find(".modal-del-btn").on("click", async function() {
    $(filterModalId).modal("hide");

    const id = parseInt($(filterModalId).data("primary-key"));
    const filter = $(filterTableId).DataTable().row((idx, row) => { return row.id === id }).data();
    const name = sanitise(filter.name);

    const deleteFilter = async () => {
        await ajaxRequest(`/api/filters/${filter.id}/`, "DELETE");
        setTimeout(async () => {
            $(filterTableId).trigger("doDataLoad");
            await loadSubModalOptions(
                $(subModalId).find('[data-field="filters"]'),
                `/api/filters/?server=${selectedServer.id}`
            );
        }, 600);
    }

    createModal({
        title: "Delete a Content Filter",
        texts: [
            {
                content: `<span>Do you wish to permanently delete <b>${name}</b>?</span>`,
                html: true
            },
            { content: "This action is irreversible, you will lose this filter forever." }
        ],
        buttons: [
            {
                className: "btn-danger me-3",
                iconClass: "bi-trash3",
                closeModal: true,
                onClick: deleteFilter,
            },
            {
                className: "btn-secondary px-4",
                iconClass: "bi-arrow-return-right",
                closeModal: true,
                onClick: async () => $(filterModalId).modal("show")
            }
        ]
    });
});

getTableFiltersComponent(filterTableId).find(".js-tableDeleteBtn").on("click", async function() {
    const rows = getSelectedTableRows(filterTableId);
    const isMany = rows.length > 1;
    const names = rows.map(row => row.name);

    const deleteFilters = async () => {
        rows.forEach(async row => {
            await ajaxRequest(`/api/filters/${row.id}/`, "DELETE");
        });

        setTimeout(async () => {
            $(filterTableId).trigger("doDataLoad");
            await loadSubModalOptions(
                $(subModalId).find('[data-field="filters"]'),
                `/api/filters/?server=${selectedServer.id}`
            );
        }, 600);
    }

    createModal({
        title: `Delete ${isMany ? "Many Content Filters" : "Content Filter"}`,
        texts: [
            {
                content: `<p>Do you wish to permanently delete ${isMany ? "these" : "these"} content filter${isMany ? "s" : ""}?</p>`,
                html: true
            },
            {
                content: arrayToHtmlList(names, true).prop("outerHTML"),
                html: true
            }
        ],
        buttons: [
            {
                className: "btn-danger me-3",
                iconClass: "bi-trash3",
                closeModal: true,
                onClick: deleteFilters
            },
            {
                className: "btn-secondary px-4",
                iconClass: "bi-arrow-return-right",
                closeModal: true
            }
        ]
    });
});


// region New/Edit Modal

$(filterTableId).closest('.js-tableBody').siblings('.js-tableFilters').on("click", ".js-tableAddBtn", async function() {
    await openDataModal(filterModalId, -1);
});

$(filterTableId).on("click", ".edit-modal", async function() {
    const id = $(filterTableId).DataTable().row($(this).closest("tr")).data().id;
    await openDataModal(filterModalId, id, `/api/filters/${id}/`);
});

$(filterModalId).on("submit", async function(event) {
    event.preventDefault();
    await onModalSubmit(
        $(filterModalId),
        $(filterTableId),
        "/api/filters/"
    );
});


// region Load Modal Options

$(document).ready(async function() {
    await loadMatchingAlgorithms();
});

async function loadMatchingAlgorithms() {
    const $input = $(filterModalId).find('[data-field="matching_algorithm"]');
    const data = await ajaxRequest("/api/filters/", "OPTIONS");
    data.actions.GET.matching_algorithm.choices.forEach(algorithm => {
        $input.append($(
            "<option>",
            {
                text: algorithm.display_name,
                value: algorithm.value > 0 ? algorithm.value : ""
            }
        ));
    });
    if ($input.next('.corbz-select-container').length) {
        $input.next('.corbz-select-container').remove();
        $input.initCorbzSelect();
    }
}
