const fs = require('fs');

const path = 'd:/برنامج مخازن/app_final.js';
const newModulePath = 'd:/برنامج مخازن/entities_module.js';

let content = fs.readFileSync(path, 'utf8');
const lines = content.split(/\r?\n/);

let extractedLines = [];
let insideTargetBlock = false;
let bracesCount = 0;

function extractBlock(startRegex) {
    let block = [];
    let isInside = false;
    let bCount = 0;
    for (let i = 0; i < lines.length; i++) {
        if (!isInside && startRegex.test(lines[i])) {
            isInside = true;
            bCount = 0;
        }
        if (isInside) {
            block.push(lines[i]);
            if (lines[i].includes('{')) bCount += (lines[i].match(/{/g) || []).length;
            if (lines[i].includes('}')) bCount -= (lines[i].match(/}/g) || []).length;
            
            // if bCount goes back to 0, we found the end
            if (bCount === 0) {
                isInside = false;
                // Add an empty line
                block.push('');
            }
        }
    }
    return block;
}

// 1. Modals
const modalPatterns = [
    /window\.openUserModal\s*=/,
    /window\.openWarehouseModal\s*=/,
    /window\.openContactModal\s*=/,
    /window\.openUnitModal\s*=/,
    /window\.openItemModal\s*=/
];

// 2. Delete functions
const deletePatterns = [
    /window\.deleteItem\s*=/,
    /window\.deleteWarehouse\s*=/,
    /window\.deleteContact\s*=/,
    /window\.deleteUnit\s*=/,
    /window\.deleteUser\s*=/
];

// 3. Save listeners
const savePatterns = [
    /document\.getElementById\('btn-save-user'\)\.addEventListener/,
    /document\.getElementById\('btn-save-warehouse'\)\.addEventListener/,
    /document\.getElementById\('btn-save-item'\)\.addEventListener/,
    /document\.getElementById\('btn-save-unit'\)\.addEventListener/,
    /document\.getElementById\('btn-save-contact'\)\.addEventListener/
];

for (let p of modalPatterns) extractedLines.push(...extractBlock(p));
for (let p of deletePatterns) extractedLines.push(...extractBlock(p));
for (let p of savePatterns) extractedLines.push(...extractBlock(p));

if (extractedLines.length > 0) {
    fs.writeFileSync(newModulePath, extractedLines.join('\n'), 'utf8');
    console.log('Entities module extracted to ' + newModulePath);
    console.log('Total extracted lines: ' + extractedLines.length);
} else {
    console.log('Nothing extracted.');
}
