import { app, BrowserWindow, ipcMain, protocol, shell, net as electronNet } from 'electron'
import { join } from 'path'
import { electronApp, is, optimizer } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset'
import { PipeClient } from './client'
import { handleFile, unlockProjectFolder } from './files'
import { ensurePipeServerRunning, stopSpawnedPipeServer } from './pipe-server'

let pipeClient: PipeClient | null = null
let pipeStartupSettled = false

function createWindow(): void {
  const mainWindow = new BrowserWindow({
    width: 1920,
    height: 1080,
    show: false,
    autoHideMenuBar: true,
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false
    }
  })

  mainWindow.removeMenu()

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

  mainWindow.on('closed', () => {
    pipeClient?.destroy()
    pipeClient = null
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }

  if (is.dev) {
    mainWindow.webContents.openDevTools()
  }

  pipeClient?.destroy()
  pipeClient = new PipeClient(mainWindow)
}

app.whenReady().then(async () => {
  electronApp.setAppUserModelId('com.electron')

  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  ipcMain.on('ping', () => console.log('pong'))
  ipcMain.on('connect-pipe', () => {
    if (!pipeStartupSettled) {
      return
    }

    pipeClient?.connect()
  })
  ipcMain.on('disconnect-pipe', () => {
    pipeClient?.disconnect()
  })
  ipcMain.on('pipe-end', () => {
    pipeClient?.disconnect()
  })

  handleFile()

  protocol.handle('local', (request) => {
    const filePath = request.url.slice('local://'.length)
    return electronNet.fetch(`file://${filePath}`.toString())
  })

  createWindow()

  try {
    await ensurePipeServerRunning()
  } catch (error) {
    console.error('[pipe] ensurePipeServerRunning failed:', error)
  }

  pipeStartupSettled = true
  pipeClient?.connect()

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

app.on('before-quit', () => {
  pipeClient?.destroy()
  stopSpawnedPipeServer()
  unlockProjectFolder()
})

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