const fs = require('fs');

const path = 'd:/برنامج مخازن/entities_module.js';
let content = fs.readFileSync(path, 'utf8');

const buttons = ['user', 'warehouse', 'item', 'unit', 'contact'];

for (let btn of buttons) {
    const searchStr = `document.getElementById('btn-save-${btn}').addEventListener('click', async () => {`;
    const replaceStr = `
(function() {
    let oldBtn = document.getElementById('btn-save-${btn}');
    if (oldBtn) {
        let newBtn = oldBtn.cloneNode(true);
        oldBtn.parentNode.replaceChild(newBtn, oldBtn);
        newBtn.addEventListener('click', async () => {`;
    
    // Replace the opening
    content = content.replace(searchStr, replaceStr);
    
    // We also need to add `})();` at the very end of the function block.
    // Wait, since we are doing this globally, the end of the block is tricky to find via regex.
    // BUT we don't have to wrap it in an IIFE!
    // We can just define block-scoped variables using `let` inside a block `{}`.
}

// Actually, to make finding the end of block unnecessary, we can just do:
content = content.replace(/document\.getElementById\('btn-save-([a-zA-Z0-9_-]+)'\)\.addEventListener\('click',\s*async\s*\(\)\s*=>\s*\{/g, 
    `{ 
        let __oldBtn = document.getElementById('btn-save-$1'); 
        if (__oldBtn) { 
            let __newBtn = __oldBtn.cloneNode(true); 
            __oldBtn.parentNode.replaceChild(__newBtn, __oldBtn); 
            __newBtn.addEventListener('click', async () => {`);

// Now we need to balance the `{` we added at the beginning of the replacement.
// But wait! If we added a `{`, we need a `}` at the end. That's hard to inject automatically.
// Let's use a simpler DOM trick!
// Instead of replacing the event listener wrapper, we just PREPEND the clone logic at the top of the file!

let prependLogic = `
// Strip old listeners from app_final.js
['btn-save-user', 'btn-save-warehouse', 'btn-save-item', 'btn-save-unit', 'btn-save-contact'].forEach(id => {
    let oldBtn = document.getElementById(id);
    if (oldBtn) {
        let newBtn = oldBtn.cloneNode(true);
        oldBtn.parentNode.replaceChild(newBtn, oldBtn);
    }
});\n\n`;

// Since the file currently just has `document.getElementById('btn-save-X').addEventListener`, 
// they will now target the NEW cloned button! The old listeners from app_final.js will be destroyed.

fs.writeFileSync(path, prependLogic + content, 'utf8');
console.log('Fixed listeners successfully');
