const { app, BrowserWindow, ipcMain, dialog } = require('electron');
const path = require('path');
const fs = require('fs');
const downloader = require('./utils/downloader');

let mainWindow;
let selectedOutputDir = app.getPath('downloads');

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 900,
    height: 700,
    minWidth: 800,
    minHeight: 600,
    frame: false, // Make window frameless
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      contextIsolation: true,
      nodeIntegration: false
    },
    show: false
  });

  const { Menu } = require('electron');
  Menu.setApplicationMenu(null); // Hide the default menu bar

  mainWindow.loadFile(path.join(__dirname, 'src', 'index.html'));

  // Open devtools if needed in development
  // mainWindow.webContents.openDevTools();

  mainWindow.once('ready-to-show', () => {
    mainWindow.show();
  });
}

// IPC Handlers for custom titlebar controls
ipcMain.on('window-minimize', () => {
  if (mainWindow) mainWindow.minimize();
});

ipcMain.on('window-close', () => {
  if (mainWindow) mainWindow.close();
});

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

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

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

// IPC Handler: Dependency Check
ipcMain.handle('check-dependencies', async () => {
  try {
    await downloader.checkDependencies((message, progress) => {
      if (mainWindow) {
        mainWindow.webContents.send('dependency-status', { message, progress });
      }
    });
    return { success: true };
  } catch (error) {
    return { success: false, error: error.message };
  }
});

// IPC Handler: Get Video Details
ipcMain.handle('get-video-info', async (event, { url, browser }) => {
  try {
    const info = await downloader.getVideoInfo(url, browser);
    return { success: true, info };
  } catch (error) {
    return { success: false, error: error.message };
  }
});

// IPC Handler: Download Media
ipcMain.handle('download-media', async (event, { items, browser }) => {
  try {
    const result = await downloader.downloadMedia(items, selectedOutputDir, browser, (progressData) => {
      if (mainWindow) {
        mainWindow.webContents.send('download-progress', progressData);
      }
    });
    return result;
  } catch (error) {
    return { success: false, error: error.message };
  }
});

// IPC Handler: Pause Download
ipcMain.handle('pause-download', () => {
  return downloader.pauseDownload();
});

// IPC Handler: Resume Download
ipcMain.handle('resume-download', () => {
  return downloader.resumeDownload();
});

// IPC Handler: Stop Download
ipcMain.handle('stop-download', () => {
  return downloader.stopDownload();
});

// IPC Handler: Open Path in File Explorer
ipcMain.handle('open-path', async (event, folderPath) => {
  try {
    const { shell } = require('electron');
    await shell.openPath(folderPath);
    return { success: true };
  } catch (error) {
    return { success: false, error: error.message };
  }
});

// IPC Handler: Select Output Directory
ipcMain.handle('select-directory', async () => {
  const result = await dialog.showOpenDialog(mainWindow, {
    properties: ['openDirectory'],
    defaultPath: selectedOutputDir
  });
  if (!result.canceled && result.filePaths.length > 0) {
    selectedOutputDir = result.filePaths[0];
    return selectedOutputDir;
  }
  return selectedOutputDir;
});

// IPC Handler: Get Default Downloads Folder
ipcMain.handle('get-downloads-folder', () => {
  return selectedOutputDir;
});
