import { dialog, ipcMain } from 'electron'
import { listSnapshots } from '../ddev'
import { runStreamed } from '../commandRunner'

export function registerDatabaseIpc(): void {
  ipcMain.handle('database:listSnapshots', (_event, name: string, approot: string) =>
    listSnapshots(name, approot)
  )

  ipcMain.handle(
    'database:createSnapshot',
    (event, operationId: string, approot: string, snapshotName?: string) =>
      runStreamed(
        operationId,
        ['snapshot', ...(snapshotName ? ['--name', snapshotName] : [])],
        event.sender,
        { cwd: approot }
      )
  )

  ipcMain.handle(
    'database:restoreSnapshot',
    (event, operationId: string, approot: string, snapshotName: string) =>
      runStreamed(operationId, ['snapshot', 'restore', snapshotName], event.sender, {
        cwd: approot
      })
  )

  ipcMain.handle(
    'database:deleteSnapshot',
    (event, operationId: string, approot: string, snapshotName: string) =>
      runStreamed(
        operationId,
        ['snapshot', '--cleanup', '--name', snapshotName, '-y'],
        event.sender,
        { cwd: approot }
      )
  )

  ipcMain.handle(
    'database:importFile',
    (event, operationId: string, approot: string, filePath: string) =>
      runStreamed(operationId, ['import-db', `--file=${filePath}`], event.sender, { cwd: approot })
  )

  ipcMain.handle(
    'database:exportFile',
    (event, operationId: string, approot: string, filePath: string) =>
      runStreamed(operationId, ['export-db', `--file=${filePath}`], event.sender, { cwd: approot })
  )

  ipcMain.handle('database:pickImportFile', async () => {
    const result = await dialog.showOpenDialog({
      properties: ['openFile'],
      filters: [
        { name: 'SQL dumps', extensions: ['sql', 'gz', 'zip', 'bz2', 'xz', 'tgz'] },
        { name: 'All files', extensions: ['*'] }
      ]
    })
    return result.canceled ? null : result.filePaths[0]
  })

  ipcMain.handle('database:pickExportPath', async (_event, defaultFileName: string) => {
    const result = await dialog.showSaveDialog({
      defaultPath: defaultFileName,
      filters: [
        { name: 'SQL dumps', extensions: ['sql', 'gz'] },
        { name: 'All files', extensions: ['*'] }
      ]
    })
    return result.canceled ? null : result.filePath
  })
}
