import { app } from 'electron'
import log from 'electron-log'
import path from 'node:path'
import { WindowManager } from './window-manager'
import { readFileObject } from 'app/src-electron/utils/file'

/**
 * Open File Manager: Handle file associations
 */
export class OpenFileManager {
  private pendingFilePath: string | null = null

  constructor() {
    this.init()
  }

  init() {
    log.info('Init OpenFileManager')
    this.pendingFilePath = null
  }

  onOpenFile(args: string[], source = '') {
    log.info(`🍃[${source}] Parsing args:`, args)

    const filePath = args.find(arg => {
      const cleanArg = arg.replace(/^"(.*)"$/, '$1')

      return path.isAbsolute(cleanArg) &&
        cleanArg !== process.execPath &&
        !cleanArg.includes('node_modules') &&
        !cleanArg.startsWith('--')
    })

    if (filePath) {
      const cleanPath = filePath.replace(/^"(.*)"$/, '$1')
      log.info(`🍃[${source}] Found valid file path:`, cleanPath)
      this.sendFile(cleanPath, source)
    } else {
      log.info(`🍃 [${source}] No valid book file path found in arguments.`)
    }
  }

  async sendFile(filePath: string, source = '') {
    // Exclude js files
    if (filePath.endsWith('.js')) {
      return
    }

    const mainWindow = WindowManager.getMainWindow()
    if (app.isReady() && mainWindow && !mainWindow.isDestroyed()) {
      if (mainWindow.webContents.isLoading()) {
        this.pendingFilePath = filePath
      } else {
        const file = await readFileObject(filePath)
        this.sendAppEvent('open-file', {
          path: filePath,
          file: file,
          source: source
        })
      }
    } else {
      this.pendingFilePath = filePath
      WindowManager.createMainWindow(`openFileManager: ${filePath}`)
    }
  }

  getFile() {
    if (this.pendingFilePath) {
      this.sendFile(this.pendingFilePath, 'get-file')
      this.pendingFilePath = null
    }
  }

  sendAppEvent(event: string, data?: any) {
    WindowManager.getMainWindow()?.webContents.send('app-event', event, data)
  }
}

export const openFileManager = new OpenFileManager()
