const { app, contextBridge, ipcRenderer  } = require('electron');
const fs = require('fs');
// const path = require('path');
// const process = require('process');

var settingvalues={
   trace: true,
   tracefilter: 'DAIMWEFO',
   log: "./backend/data_0/frontend/logs/frontend_#YYYY-#MM-#DD.log"
}
var flexsettings = {
  GetSetting: function(key,defval) {
      if ( settingvalues[key] != null) return settingvalues[key];
      return defval;
  },
  GetIntSetting: function (key, defval) {
    if ( settingvalues[key] != null) return settingvalues[key];
    return defval;
  },
  GetBooleanSetting: function (key, defval) {
    if ( settingvalues[key] != null) return settingvalues[key];
    return defval;
  },
  GetDataPath: function( ) {
    return process.cwd();
  }
 }
var syncFs = {
  cwd  : function ( ) {
    return process.cwd();
  },
  existsSync: function (fpath ) {
    return fs.existsSync(fpath);
  },
  readFileSync: function ( fpath, enc) {
    return fs.readFileSync(fpath, enc);
  },
  writeFileSync: function( fpath, data) {
    return fs.writeFileSync(fpath, data);
  }
}
 var trace = require('./diagtrace.js')(flexsettings);
 contextBridge.exposeInMainWorld('SATELNDEBEAPI', {
  company: "SATEL",
  versions: { node: process.versions.node,
              chrome: process.versions.chrome,
              electron: process.versions.electron
            },
  trace: trace,
  syncFs: syncFs,
  cwd:  process.cwd()  // 2023-03-23 share cwd/pwd
  //,argv:  process.argv  // 2023-03-23 share cmdline params
});

// All of the Node.js APIs are available in the preload process.
// It has the same sandbox as a Chrome extension.
var logs = [];

function absToRel( logs, tagname, property) {
  var filecwd = 'file:///' + process.cwd().split("\\").join('/'); // "file:///D:/_wsl/_output_..."
  var elems = document.getElementsByTagName(tagname);
  for (var i = 0; i < elems.length; i++) {
    var old=elems[i][property];
    logs.push( "unmod (fcwd.l=" +filecwd.length+") " + tagname + '[' + i + ']: ' +  elems[i][property]);
    // input like:
    // file:///D:/_wsl/_output_2024-08-26_0945/output/electron/resources/app/favicon.ico
    // process.cwd like (in Windows):
    // (file:///)D:\_wsl\_output_2024-08-26_0956\output\electron
    // must be converted to
    // file:///D:/_wsl/_output_2024-08-26_0945/output/electron

    // EX:  if ((elems[i][property]) && (elems[i][property][0] =='/')) {
    if ((elems[i][property]) && ( elems[i][property].indexOf(filecwd)==0)) {
      // Absolute path detected !!
      var oldurl = elems[i][property].toString();
      var newurl = "file:///." + oldurl.substring(filecwd.length);
      elems[i][property] = newurl;
      logs.push( "mod " + tagname + '[' + i + ']: ' + old + ' -> ' +  elems[i][property] + " = " + newurl);
    }
  }
}

function modifyLinks( showAlert) {
  //const imagePath = path.join(app.getAppPath(), 'index.html');
  var appP  = "error";
  try { appP = process.cwd();}
  catch(err) {
    appP = err;
  }
  logs.push("getAppPath: " + appP);
  // logs.push("process.cwd: " + process.cwd());
  // modify all anchors to not be absolute...
  absToRel(logs, 'a', 'href');
  absToRel(logs, 'link', 'href');
  absToRel(logs, 'script', 'src');
  absToRel(logs, 'img', 'src');
  if (showAlert) {
    //logs.forEach( l => {console.log(l);});
    // fs.writeFileSync( 'preload_debug.txt', logs.join("\r\n").toString());
    // alert("Modified:\r\n" + logs.join("\r\n").toString() );
  }
}

// Expose a safe API to the renderer process
contextBridge.exposeInMainWorld('electronAPI', {
  getErrorInfo: () => ipcRenderer.invoke('get-error-info')
});

window.addEventListener('load', (event) => {
  modifyLinks( true );
});

window.addEventListener('DOMContentLoaded', () => {
  const replaceText = (selector, text) => {
    const element = document.getElementById(selector)
    if (element) element.innerText = text
  }

  for (const type of ['chrome', 'node', 'electron']) {
    replaceText(`${type}-version`, process.versions[type])
  }

  // hhmm...css files will not be okay based on above though...
  //modifyLinks( false );
})
