import "@johnlindquist/kit"
import { Action } from "@johnlindquist/kit"
import { URL, fileURLToPath } from "url"
import * as path from 'path';
const includeSingleFiles = false
let filename = home("Library", "Application Support", "Code", "User", "globalStorage", "state.vscdb")
if (isWin) filename = home("AppData", "Roaming", "Code", "User", "globalStorage", "state.vscdb")
let { default: sqlite3 } = await import("sqlite3")
let { open } = await import("sqlite")
const db = await open({
  filename,
  driver: sqlite3.Database,
})
let key = `history.recentlyOpenedPathsList`
let table = `ItemTable`
let result = await db.get(`SELECT * FROM ${table} WHERE key = '${key}'`)
let recentPaths = JSON.parse(result.value)
let recentFilePaths: Action[] = []
for (const entry of recentPaths.entries) {
  
  if (entry.folderUri) {
    if (entry.folderUri.startsWith("file://")) {
      
      let path = fileURLToPath(new URL(entry.folderUri))
      const label = getLabelFromPath(path)
      if (path.includes(":\\")) {
        path = getCapitalizedPath(path)
      }
      recentFilePaths.push({name: label ?? "fallback", description: path, value: path})
    } else if ((entry.folderUri.startsWith("vscode-remote://") || entry.folderUri.startsWith("vscode-vfs://"))) {
      
      const label = entry.label ?? getLabelFromPath(entry.folderUri, true);
      
      const value = `--folder-uri=${entry.folderUri}`
      recentFilePaths.push({name: label, description: entry.folderUri, value: value})
    }
  } else {
    
    
    if (includeSingleFiles) {
      try {
        const path = fileURLToPath(new URL(entry.fileUri))
        const label = getLabelFromPath(path)
        recentFilePaths.push({name: label, description: path, value: path})
      } catch (error) {
        
        console.error(`Failed to parse ${entry.folderUri}. Error: ${error}`)
      }
    }
  }
}
let recentPath = await arg("Open recent project", recentFilePaths)
hide()
await exec(`code ${recentPath}`)
function getLabelFromPath(inPath: string, isRemote = false) {
  const outPathBase = path.basename(inPath)
  if (!isRemote) {
    return outPathBase
  } else {
    const parts = inPath.split("%2B");
    const protocol = parts[0].split("://")[1].replaceAll("-remote", "").toUpperCase();
    const host = parts[1].split("/")[0];
    return `${outPathBase} [${protocol}: ${host}]`
  }
}
function getCapitalizedPath(path: string) {
  const firstCharNew = path.charAt(0).toUpperCase();
  const slicedPath = path.slice(1)
  return firstCharNew + slicedPath;
}