// Open the Advanced Text Editor and start editing a file.

import { readdirSync } from "fs"
import { join, extname } from "path"

import type { CommandOutput } from "@/shared/types"
import { isBinaryFile } from "@/utils"
import { countChar } from "@/shared/utils"
import { projectName, projectDir } from "@/project"
import { sessionGet } from "@/session"

export default async function (path: string) {
  const root = sessionGet("cwd") || projectDir()

  let files: string[] = []

  for (const file of readdirSync(root, { withFileTypes: true })) {
    files.push(file.name)
  }

  if (files.includes(path))
    return await readFile(join(root, path))
  else
    return await newFile(join(root, path))
}

async function readFile(path: string): Promise<CommandOutput> {
  const ext = extname(path).slice(1)
  const file = Bun.file(path)

  if (await isBinaryFile(path))
    throw "Cannot display binary file"

  const text = await file.text()
  const rows = countChar(text, "\n") + 1

  return <textarea class="editor" spellcheck={false} rows={rows} data-path={path}>{text}</textarea>

}

async function newFile(path: string): Promise<CommandOutput> {
  return <textarea class="editor" spellcheck={false} rows={1} data-path={path}></textarea>
}
