import { exec } from "child_process"
import * as os from "os"
import * as path from "path"
import cli from "cli-ux"

const checkXDGInstalled = (): Promise<boolean> => {
  return new Promise((resolve, reject) => {
    exec("which xdg-open", (error, stdout, stderr) => {
      if (error) {
        resolve(false)
      }

      if (stdout) {
        resolve(true)
      } else {
        resolve(false)
      }
    })
  })
}

const openFile = (filePath: string): void => {
  const fullPath = path.join(process.cwd(), filePath)
  let command: string

  switch (os.platform()) {
    case "darwin": // macOS
      command = `open ${fullPath}`
      break
    case "win32": // Windows
      command = `start ${fullPath}`
      break
    case "linux": // Linux
      command = `xdg-open ${fullPath}`
      break
    default:
      throw new Error("Unsupported OS")
  }

  exec(command, (error, stdout, stderr) => {
    if (error) {
      console.error(`exec error: ${error}`)
    }
  })
}

const eventManager = {
  enqueue: (event: string, data: any) => {
    if (event === "start_exercise") {
      const exercise = data
      const filesToOpen = exercise.files
        .filter((file: any) => !file.hidden)
        .map((file: any) => {
          return file.path.replace("\\", "/")
        })

      for (const file of filesToOpen) {
        openFile(file)
      }
    }

    if (event === "open_files") {
      const files = data

      for (const file of files) {
        const correctedPath = file.replace("\\", "/")
        openFile(correctedPath)
      }
    }

    if (event === "open_window") {
      const url = data.url
      cli.open(url)
    }
  },
  checkXDGInstalled,
}

export { eventManager }
