var ruleRowTemplate = '<tr class="border-bottom" id="rule-[INDEX]">' +
    '                <td class="align-middle"><p class="mb-0">[INDEX]</p></td>' +
    '                <td class="align-middle"><input type="text" class="form-control rule-input-str-input" placeholder="String to replace" value="[STR-TO-REPLACE]"></td>' +
    '                <td class="align-middle"><input type="text" class="form-control rule-output-str-input" placeholder="Replace with" value="[REPLACE-STR]"></td>' +
    '                <td class="align-middle">' +
    '                    <label class="toggle-switch">' +
    '                        <input class="rule-enabled-by-default-toggle" type="checkbox" [ENABLED]>' +
    '                        <div class="toggle-switch-background">' +
    '                            <div class="toggle-switch-handle"></div>' +
    '                        </div>' +
    '                    </label>' +
    '                </td>' +
    '                <td class="align-middle">' +
    '                    <label class="toggle-switch">' +
    '                        <input class="ignore-case-toggle" type="checkbox" [IGNORECASE]>' +
    '                        <div class="toggle-switch-background">' +
    '                            <div class="toggle-switch-handle"></div>' +
    '                        </div>' +
    '                    </label>' +
    '                </td>' +
    '                <td class="align-middle">' +
    '                    <button class="btn btn-danger rule-trash-btn">' +
    '                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-trash" viewBox="0 0 16 16">' +
    '                            <path d="M5.5 5.5A.5.5 0 0 1 6 6v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5m2.5 0a.5.5 0 0 1 .5.5v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5m3 .5a.5.5 0 0 0-1 0v6a.5.5 0 0 0 1 0z"/>' +
    '                            <path d="M14.5 3a1 1 0 0 1-1 1H13v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V4h-.5a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1H6a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1h3.5a1 1 0 0 1 1 1zM4.118 4 4 4.059V13a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1V4.059L11.882 4zM2.5 3h11V2h-11z"/>' +
    '                        </svg>' +
    '                    </button>' +
    '                </td>' +
    '            </tr>';
var configJson = {};

$("document").ready(function() {
    loadConfig();

    $("#add-rule-btn").click(function() {
        appendRow(generateRowTemplate("", "", true, true));
    });

    $("#export-rules-btn").click(async () => {
        console.log("Exporting rules...");
        buildAndSaveConfig();
        await Neutralino.clipboard.writeText(JSON.stringify(configJson));
    });

    $("#import-rules-btn").click(async () => {
        console.log("Importing rules...");
        const importedConfig = await Neutralino.clipboard.readText();
        if (importedConfig) {
            try {
                configJson = JSON.parse(importedConfig);
                $(".table tbody").empty();
                configJson["rules"].forEach(function(rule) {
                    appendRow(generateRowTemplate(rule["strToReplace"], rule["replaceStr"], rule["enabled"], rule["ignoreCase"]));
                });
                updateRowIndexes();
                buildAndSaveConfig();
            } catch (error) {
                console.error(error);
            }
        } });

    $(document).on("click", ".rule-trash-btn", function() {
        $(this).closest("tr").remove();
        updateRowIndexes();
        buildAndSaveConfig();
    });
    bindChangeEvents();
});

function appendRow(rowTemplate) {
    $(".table tbody").append(rowTemplate);
    bindChangeEvents();
    updateRowIndexes();
}

function generateRowTemplate(str, outputStr, enabled, ignoreCase) {
    var row = ruleRowTemplate;
    row = row.replaceAll("[INDEX]", $(".table tbody tr").length + 1);
    row = row.replace("[STR-TO-REPLACE]", str);
    row = row.replace("[REPLACE-STR]", outputStr);
    if (enabled) {
        row = row.replace("[ENABLED]", "checked");
    } else {
        row = row.replace("[ENABLED]", "");
    }

    if(ignoreCase){
        row = row.replace("[IGNORECASE]", "checked");
    } else {
        row = row.replace("[IGNORECASE]", "");
    }
    return row;
}

function updateRowIndexes() {
    $(".table tbody tr").each(function(index) {
        $(this).attr("id", "rule-" + (index + 1));
        $(this).find("td:first p").text(index + 1);
    });
}

function buildAndSaveConfig() {
    // Show saving status
    $("#saving-status").show();
    $("#saved-status").hide();

    var rules = [];
    $(".table tbody tr").each(function() {
        var rule = {};
        rule["strToReplace"] = $(this).find(".rule-input-str-input").val();
        rule["replaceStr"] = $(this).find(".rule-output-str-input").val();
        rule["enabled"] = $(this).find(".rule-enabled-by-default-toggle").is(":checked");
        rule["ignoreCase"] = $(this).find(".ignore-case-toggle").is(":checked");
        rules.push(rule);
    });
    configJson["rules"] = rules;
    console.log(configJson);
    window.localStorage.setItem("config", JSON.stringify(configJson));

    // Simulate a delay for saving process
    setTimeout(function() {
        $("#saving-status").hide();
        $("#saved-status").show();
    }, 200);
}

function loadConfig() {
    var config = window.localStorage.getItem("config");
    if (config) {
        configJson = JSON.parse(config);
        configJson["rules"].forEach(function(rule) {
            appendRow(generateRowTemplate(rule["strToReplace"], rule["replaceStr"], rule["enabled"], rule["ignoreCase"]));
        });
    }
    $("#saving-status").hide();
    $("#saved-status").show();
    bindChangeEvents();
}

function bindChangeEvents() {
    $(".rule-input-str-input, .rule-output-str-input").off("input").on("input", function() {
        buildAndSaveConfig();
    });
    $(".rule-enabled-by-default-toggle").off("change").on("change", function() {
        buildAndSaveConfig();
    });
    $(".ignore-case-toggle").off("change").on("change", function() {
        buildAndSaveConfig();
    });
}