import { app, BrowserWindow, screen, session, shell, dialog, ipcMain } from 'electron';
// import InitRecorder from './modules/HeadlessController';
import InitRecorder from './modules/HeadlessController/newIndex';
import Func from './apis/initClient';
import { EVENT_NAMES } from './constants/define';
import * as electronStore from './utilities/electronStore'
const path = require('path');
const pie = require('puppeteer-in-electron');
const fs = require('fs');

let mainWindow = null;
let deeplinkingUrl = '';

(async () => {
  await pie.initialize(app);
})();

if (require('electron-squirrel-startup')) {
  app.quit();
}


// 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', async () => {
  try {
    // 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 (BrowserWindow.getAllWindows().length === 0) {
      const mainWindow = await createWindow();
      // listen on all grpc events
      Func();

      // init recorder events
      // InitRecorder(pie, mainWindow);
      const initRecorder = new InitRecorder({ pie, mainWindow });
      initRecorder.init();


      // remember user login
      




      // remember user login
      



      ipcMain.on(EVENT_NAMES.COMMON.SAVE_CSV_FILE, (_, data) => {
        dialog
          .showSaveDialog({
            title: 'Save CSV',
            defaultPath: `${data?.filename}.csv`,
            filters: [{ name: 'CSV Files', extensions: ['csv'] }],
          })
          .then((result) => {
            if (!result.canceled && result.filePath) {
              fs.writeFile(result.filePath, data?.csv, (err) => {
                if (err) {
                  // Add your error handling here
                  console.error('Error writing CSV file', err);
                }
              });
            }
          })
          .catch((err) => {
            // Add your error handling here
            console.error(err);
          });


      });
    }



    // const userData = electronStore.get('user');
    //   if (userData && userData.token) {
    //     setTimeout(() => {
    //       // Gửi thông tin người dùng qua renderer process
    //       try {
    //         mainWindow.webContents.send('user-data', userData);
    //         console.log("check10===================================", userData);
    //       } catch (err) {
    //         console.log(err);
    //       }
    //     }, 3000); // Chờ  trước khi gửi dữ liệu
    //   }


      
  } catch (error) {
    console.log('hi');
  }
  
});

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

app.on('activate', () => {
  // On OS X 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 (mainWindow === null) {
    createWindow();
  }
});

app.on('before-quit', async () => {
  // Clear Service Worker data before quitting
  await session.defaultSession.clearStorageData({
    storages: ['serviceworkers'],
  });
});



app.on('open-url', async (event, url) => {
  // event.preventDefault();

  // Parse the URL and handle the "reset-password" path
  // Show the password reset page
  // Ensure the window is visible and focused

  deeplinkingUrl = url;
  if (mainWindow) {
    if (url.startsWith(`automation-scaping-tool://reset-password?token=`)) {
      mainWindow.webContents.send(EVENT_NAMES.COMMON.NAVIGATE_CHANGE_PASSWORD_PAGE, url.split('?')[1]);
    }
  } else {
    await createWindow();
    mainWindow.webContents.send(EVENT_NAMES.COMMON.NAVIGATE_CHANGE_PASSWORD_PAGE);
  }
});


// kiẻm tra yêu cầu data từ renderprocess
ipcMain.on('request-user-data', async (event) => {
  const userData = electronStore.get('user');
  if (userData) {
    event.reply('user-data', userData);
  }
});



// Sử dụng setInterval để kiểm tra sự thay đổi mỗi x mili giây



const createWindow = async () => {
  const { width, height } = screen.getPrimaryDisplay().workAreaSize;

  // Create the browser window.
  mainWindow = new BrowserWindow({
    width,
    height,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      nodeIntegration: true,
    },
  });

  // and load the index.html of the app.
  if (MAIN_WINDOW_VITE_DEV_SERVER_URL) {
    mainWindow.loadURL(MAIN_WINDOW_VITE_DEV_SERVER_URL);
  } else {
    mainWindow.loadFile(path.join(__dirname, '..', 'renderer', `${MAIN_WINDOW_VITE_NAME}`, 'index.html'));
  }

  // Open the DevTools.
  // check is development in Electron
  // if (process.env.NODE_ENV === 'development') {
  // mainWindow.webContents.openDevTools();
  // }
  // Emitted when the window is closed.
  mainWindow.on('closed', function () {
    // 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.
    mainWindow = null;
  });

  return mainWindow;
};
