////
// Each browser tab is a shell session. This means you can run multiple sessions
// in the same browser.

import type { SessionStartMessage, SessionUpdateMessage } from "@/shared/types"
import { browserCommands } from "./commands"
import { randomId } from "../shared/utils"
import { $ } from "./dom"

export const sessionId = randomId()
export const projectName = $("project-name") as HTMLAnchorElement
export const projectCwd = $("project-cwd") as HTMLAnchorElement
export const sessionStore = new Map<string, string>()

export function handleSessionStart(msg: SessionStartMessage) {
    sessionStore.set("NOSE_DIR", msg.data.NOSE_DIR)
    updateProjectName(msg.data.project)
    updateCwd(msg.data.cwd)
    browserCommands.mode?.(msg.data.mode)
}

export function handleSessionUpdate(msg: SessionUpdateMessage) {
    const data = msg.data as Record<string, string>

    if (data.project)
        updateProjectName(data.project)

    if (data.cwd)
        updateCwd(data.cwd)
}

function updateProjectName(project: string) {
    sessionStore.set("project", project)
    projectName.textContent = project
    updateCwd("/")
}

function updateCwd(cwd: string) {
    cwd = displayProjectPath(cwd)
    sessionStore.set("cwd", cwd)
    projectCwd.textContent = cwd
}

function displayProjectPath(path: string): string {
    let prefix = sessionStore.get("NOSE_DIR") || ""
    prefix += "/" + sessionStore.get("project")

    return path.replace(prefix, "") || "/"
}