const { contextBridge, ipcRenderer, app, BrowserWindow, ipcMain, dialog, Menu } = require('electron');
const { autoUpdater } = require('electron-updater');
const os = require('os');
const path = require('path');
const url = require('url');
const isDev = require('electron-is-dev');
const log = require('electron-log');
const { startLndProcess, startBtcdProcess } = require('./lnd-child-process');
const { initPythonProcess } = require('./python-child-process');
const grcpClient = require('./grpc-client');
const {
  PREFIX_NAME,
  LND_PORT,
  LND_PEER_PORT,
  LND_REST_PORT,
  LND_PROFILING_PORT,
  LND_INIT_DELAY,
  BTCD_MINING_ADDRESS,
  AUTO_UPDATE_ENABLED,
} = require('../src/config');

console.log(`
 ___       ________       ________  ________  ________
|\\  \\     |\\   ___  \\    |\\   __  \\|\\   __  \\|\\   __  \\
\\ \\  \\    \\ \\  \\\\ \\  \\   \\ \\  \\|\\  \\ \\  \\|\\  \\ \\  \\|\\  \\
 \\ \\  \\    \\ \\  \\\\ \\  \\   \\ \\   __  \\ \\   ____\\ \\   ____\\
  \\ \\  \\____\\ \\  \\\\ \\  \\   \\ \\  \\ \\  \\ \\  \\___|\\ \\  \\___|
   \\ \\_______\\ \\__\\\\ \\__\\   \\ \\__\\ \\__\\ \\__\\    \\ \\__\\
    \\|_______|\\|__| \\|__|    \\|__|\\|__|\\|__|     \\|__|


`);

const userDataPath = app.getPath('userData');
console.log(userDataPath);
//const lndSettingsDir = path.join(isDev ? '/data' : userDataPath, 'lnd');
//const btcdSettingsDir = path.join(isDev ? '/data' : userDataPath, 'btcd');
const lndSettingsDir = path.join(userDataPath, 'lnd');
const btcdSettingsDir = path.join(userDataPath, 'btcd');
console.log(lndSettingsDir);
console.log(btcdSettingsDir);
const lndArgs = process.argv.filter(a =>
  /(^--bitcoin)|(^--btcd)|(^--neutrino)/.test(a)
);

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let win;
let lndProcess;
let btcdProcess;
let pythonProcess;

log.transports.console.level = 'info';
log.transports.file.level = 'info';
ipcMain.on('log', (event, arg) => log.info(...arg));
ipcMain.on('log-error', (event, arg) => log.error(...arg));
ipcMain.on('locale-get', event =>
  event.sender.send('locale', { response: app.getLocale() })
);

let logQueue = [];
let logsReady = false;

const sendLog = log => {
  if (win && logsReady) {
    win.webContents.send('logs', log);
  } else {
    logQueue.push(log);
  }
};
const Logger = {
  info: msg => {
    log.info(msg);
    sendLog(msg);
  },
  error: msg => {
    log.error(msg);
    sendLog(`ERROR: ${msg}`);
  },
};
ipcMain.on('logs-ready', () => {
  logQueue.map(line => win && win.webContents.send('logs', line));
  logQueue = [];
  logsReady = true;
});


function createWindow() {
console.log(path.join(__dirname, 'preload.js'));
  const options = {
    width: 650,
    height: 950,
    backgroundColor: '#0f5f76',
    icon: path.join(
      __dirname,
      '..',
      'assets',
      'app-icon',
      'desktop' + ({ darwin: '.icns', win32: '.ico' }[os.platform()] || '.png')
    ),
    webPreferences: {
      nodeIntegration: true, // is default value after Electron v5
      contextIsolation: true, // protect against prototype pollution
      enableRemoteModule: false, // turn off remote
      //allowRunningInsecureContent: true,
      sandbox: false,
      preload: path.join(__dirname, 'preload.js'),
    },
  };
  if (isDev) {
    // Add width for dev tools
   options.width += 720;
   options.height += 0;
    win = new BrowserWindow(options);
    win.loadURL('http://localhost:3000');
    // Open the DevTools.
   win.webContents.openDevTools();
  } else {
  
    win = new BrowserWindow(options);
    win.loadURL(
      url.format({
        pathname: path.join(__dirname, '..', 'build', 'index.html'),
        protocol: 'file:',
        slashes: true,
      })
    );
    
  }

  // Emitted when the window is closed.
  win.on('closed', () => {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    win = null;
  });

  grcpClient.init({
    ipcMain,
    lndSettingsDir,
    lndPort: LND_PORT,
    network: isDev
      ? 'mainnet'
      : lndArgs.includes('--bitcoin.testnet')
      ? 'testnet'
      : 'mainnet',
  });
}

ipcMain.on('lnd-restart-process', async event => {
  lndProcess && lndProcess.kill('SIGINT');
  let restartError;
  try {
    lndProcess = await startLndProcess({
      isDev,
      lndSettingsDir,
      lndPort: LND_PORT,
      lndPeerPort: LND_PEER_PORT,
      logger: Logger,
      lndArgs,
    });
  } catch (err) {
    restartError = err;
  }
  event.sender.send('lnd-restart-error', { restartError });
});


ipcMain.on('pyFace', async function(event, args) {
  console.log(args.body);
  var ranID = args.body[0];
  //args.body = args.body.shift(0);
  args.body = args.body.filter(function(v){
  console.log(typeof(v));
  if(typeof(v) != 'string') return true;
  return !(v.includes('pyFace:'));
  });
  console.log(args.body, ranID);
  try {
    res = await initPythonProcess({args: args.body,logger: Logger,});
   

  } catch (err) {
    console.log(err);
    res = err
 }
   /*
    pythonProcess = "{'address': 'TTNTINGI6AKN6JBHCAOXVFZN72BAMDNBTHZ3ZRQC3ILAMWONKN7XRRQ6GM', 'amount': 0, 'amount-without-pending-rewards': 0, 'apps-local-state': [], 'apps-total-schema': {'num-byte-slice': 0, 'num-uint': 0}, 'assets': [], 'created-apps': [], 'created-assets': [], 'pending-rewards': 0, 'reward-base': 27521, 'rewards': 0, 'round': 19891151, 'status': 'Offline'}";
   */
   
   var res = JSON.stringify(res);
  event.sender.send(ranID, {response:res});
});


const startLnd = async () => {
  
   try {
   
   /*
   pythonProcess = await initPythonProcess({args: ['/data/lightning-bits/src/chains/algo/pools.py',
   '',
   '',
   '',
   '',
   '',
   'TTNTINGI6AKN6JBHCAOXVFZN72BAMDNBTHZ3ZRQC3ILAMWONKN7XRRQ6GM',
   ],logger: Logger,});
 
  
    
    btcdProcess = await startBtcdProcess({
      isDev,
      logger: Logger,
      btcdSettingsDir,
      miningAddress: BTCD_MINING_ADDRESS,
    });
  */
    lndProcess = await startLndProcess({
      isDev,
      lndSettingsDir,
      lndPort: LND_PORT,
      lndPeerPort: LND_PEER_PORT,
      lndRestPort: LND_REST_PORT,
      lndProfilingPort: LND_PROFILING_PORT,
      logger: Logger,
      lndArgs,
    });
  } catch (err) {
    Logger.error(`Caught Error When Starting lnd: ${err}`);
  }
};

// Check for updates
autoUpdater.on('update-downloaded', () => {
  const opt = {
    type: 'question',
    buttons: ['Install', 'Later'],
    title: 'Update available',
    message: 'An update is available. Restart the app and install?',
  };
  dialog.showMessageBox(win, opt, choice => {
    if (choice !== 0) return;
    setTimeout(() => autoUpdater.quitAndInstall(), 100);
  });
});

function initAutoUpdate() {
  if (isDev || AUTO_UPDATE_ENABLED !== true) return;
  autoUpdater.checkForUpdates();
  const oneHour = 60 * 60 * 1000;
  setInterval(() => autoUpdater.checkForUpdates(), oneHour);
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', () => {
  initAutoUpdate();
  createWindow();
  initApplicationMenu();
  startLnd();
});

// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  app.quit();
});

app.on('activate', () => {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (win === null) {
    createWindow();
  }
});

app.on('quit', () => {
  lndProcess && lndProcess.kill('SIGINT');
  btcdProcess && btcdProcess.kill('SIGINT');
  pythonProcess && pythonProcess.kill('SIGINT');
});

// Prevent multiple instances of the application.
const gotTheLock = app.requestSingleInstanceLock();
if (!gotTheLock) app.quit();
app.on('second-instance', (event, args) => {
  if (process.platform == 'win32') {
    const protocolUrl = args && args.slice(1)[0];
    if (protocolUrl) onOpenUrl(null, protocolUrl);
  }
  if (win) {
    if (win.isMinimized()) win.restore();
    win.focus();
  }
});


app.setAsDefaultProtocolClient(PREFIX_NAME);
const onOpenUrl = async (event, url) => {
  while (!win) {
    await new Promise(resolve => setTimeout(resolve, LND_INIT_DELAY));
  }
  win && win.webContents.send('open-url', url);
};

app.on('open-url', onOpenUrl);

process.on('uncaughtException', error => {
  Logger.error(`Caught Main Process Error: ${error}`);
});

// Create the Application's main menu
function initApplicationMenu() {
  const template = [
    {
      label: 'Edit',
      submenu: [
        { role: 'undo' },
        { role: 'redo' },
        { type: 'separator' },
        { role: 'cut' },
        { role: 'copy' },
        { role: 'paste' },
        { role: 'pasteandmatchstyle' },
        { role: 'delete' },
        { role: 'selectall' },
      ],
    },
  ];
  if (process.platform === 'darwin') {
    template.unshift({
      label: app.getName(),
      submenu: [
        { role: 'about' },
        { type: 'separator' },
        { role: 'hide' },
        { role: 'hideothers' },
        { role: 'unhide' },
        { type: 'separator' },
        { role: 'quit' },
      ],
    });
    // Edit menu
    template[1].submenu.push({ type: 'separator' });
  }
  Menu.setApplicationMenu(Menu.buildFromTemplate(template));
}
