const { app, BrowserWindow, ipcMain, BrowserView } = require('electron');
const fetch = require('node-fetch');
const path = require('path');

let view;

function createWindow () {
  const win = new BrowserWindow({
    width: 1200,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      nodeIntegration: true,
      contextIsolation: false,
    }
  });

  win.loadFile('index.html');

  view = new BrowserView();
  win.setBrowserView(view);
  view.setBounds({ x: 400, y: 0, width: 800, height: 600 });
  view.webContents.loadURL('https://electronjs.org');
}

app.whenReady().then(() => {
  createWindow();

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow();
    }
  });
});

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

ipcMain.on('load-url', (event, url) => {
  view.webContents.loadURL(url);
});

ipcMain.on('execute-js', (event, code) => {
  view.webContents.executeJavaScript(code);
});

ipcMain.on('send-message', async (event, message) => {
  try {
    const response = await fetch('http://127.0.0.1:8000/ai_chat/', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        // Note: You'll need to handle CSRF tokens and authentication if your Django app requires it.
      },
      body: `message=${encodeURIComponent(message)}`
    });

    if (response.ok) {
      const data = await response.json();
      event.reply('ai-response', data.reply);
    } else {
      event.reply('ai-response', 'Error: Could not get a response from the AI.');
    }
  } catch (error) {
    console.error(error);
    event.reply('ai-response', 'Error: Could not connect to the AI service.');
  }
});