const { ipcRenderer } = require('electron');
const path = require('path');
const fs = require('fs');

const runNeuroAd = require('./page.js');
const eventNames = require('./configs-constants/eventNames.js');
const contentController = require('./modules/page/content-controller.js');

console.debug('neuroAd_initAsSubmoduleInfo SCripts')

// document.body.innerHTML += '1111111111111111';

/*
ipcRenderer.once('neuroAd_initAsSubmoduleInfo', (event, args) => {
    const { htmlFile, appendTo } = args;

    console.debug('neuroAd_initAsSubmoduleInfo Get', { htmlFile, appendTo })

    const filePath = path.join(__dirname, htmlFile);
    let fileData = (filePath ? fs.readFileSync(filePath) : null);
    fileData = (fileData ? `${fileData.toString()}` : ``);

    if (!fileData) {
        return;
    }

    let doc = new DOMParser().parseFromString(fileData, "text/html");

    document.body.innerHTML += doc.documentElement.innerHTML;

    // document.querySelector(appendTo).insertAdjacentHTML('beforeend', fileData);
    // document.body.innerHTML += fileData;
});
*/

const init = (options) => {
    const htmlFile = options?.htmlFile || 'content.html';
    const appendTo = options?.appendTo || 'body';

    const filePath = path.join(__dirname, htmlFile);
    let fileData = (filePath ? fs.readFileSync(filePath) : null);
    fileData = (fileData ? `${fileData.toString()}` : ``);

    if (!fileData) {
        return;
    }

    fileData = fileData.replaceAll('href="./', `href="file:///${__dirname}/`);
    // fileData = fileData.replaceAll('src="./', `src="file:///${__dirname}/`);
    // fileData = fileData.replaceAll('require("./', `require("${__dirname}/`);

    let doc = new DOMParser().parseFromString(fileData, "text/html");

    document.querySelector(appendTo).innerHTML += doc.documentElement.innerHTML;
    // document.querySelector(appendTo).innerHTML += fileData;

    setImmediate(runNeuroAd);
};

module.exports = {
    nadInitRender: runNeuroAd,
    nadEventNames: eventNames,
    nadContentController: contentController
};
