import { app, BrowserWindow } from 'electron'
import { electronApp, optimizer } from '@electron-toolkit/utils'
import { mkdirSync } from 'fs'
import { join } from 'path'

import { registerIpcHandlers } from './ipc'
import { createMainWindow } from './windows/mainWindow'

if (!app.isPackaged) {
  const devDataPath = join(app.getAppPath(), '.electron-dev-data')
  const devCachePath = join(devDataPath, 'cache')

  mkdirSync(devCachePath, { recursive: true })
  app.setPath('userData', devDataPath)
  app.setPath('sessionData', devDataPath)
  app.setPath('cache', devCachePath)
}

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

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

  registerIpcHandlers()
  createMainWindow()

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

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