const fs = require('fs');

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

// We need to replace `document.getElementById('btn-save-X').addEventListener('click', ...)`
// with:
// `(function(){ let btn = document.getElementById('btn-save-X'); let newBtn = btn.cloneNode(true); btn.parentNode.replaceChild(newBtn, btn); newBtn.addEventListener('click', ...); })();`

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

for (let entity of replacements) {
    const searchStr = `document.getElementById('btn-save-${entity}').addEventListener('click',`;
    const replaceStr = `(function(){ 
        let btn = document.getElementById('btn-save-${entity}'); 
        if(btn) {
            let newBtn = btn.cloneNode(true); 
            btn.parentNode.replaceChild(newBtn, btn); 
            newBtn.addEventListener('click',`;
            
    content = content.replace(searchStr, replaceStr);
}

// We need to close the IIFE `})();` at the end of each listener block.
// Wait, doing this via string replacement is slightly tricky because we need to find the end of the addEventListener block.
// Let's do something simpler: Just append a script to `index.html` that removes the listeners BEFORE `entities_module.js` loads?
// No, the listeners are added in `app_final.js` which is loaded before `entities_module.js`.
// A better way is to override `addEventListener` temporarily or just rewrite the JS.
