////
// Temporarily display a message to the user in the status bar.

import { $ } from "./dom"
import { on } from "./event"
import { sessionStore } from "./session"
import { apps } from "./webapp"

export const projectName = $("project-name") as HTMLAnchorElement
export const projectCwd = $("project-cwd") as HTMLAnchorElement
export const projectWww = $("project-www") as HTMLAnchorElement

const statusbar = $("statusbar") as HTMLDivElement
const statusbarMsg = $("statusbar-msg") as HTMLSpanElement

const STATUS_MSG_LENGTH = 3000

let timer: NodeJS.Timeout

export function initStatusbar() {
  registerEvents()
}

function registerEvents() {
  on("apps:change", e =>
    updateWww(sessionStore.get("project") || "root")
  )

  on("session:update", (e) => {
    const ev = e as CustomEvent
    const data = ev.detail

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

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

export function status(msg: string) {
  showStatusMsg()
  statusbarMsg.textContent = msg

  if (timer) clearTimeout(timer)
  timer = setTimeout(hideStatusMsg, STATUS_MSG_LENGTH)
}

function showStatusMsg() {
  statusbar.classList.add("showing-msg")
}

function hideStatusMsg() {
  statusbar.className = ""
}

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

function updateCwd(cwd: string) {
  cwd = displayProjectPath(cwd)
  projectCwd.textContent = cwd
}

function updateWww(project: string) {
  if (!apps.includes(project) || project === "root") {
    projectWww.style.display = "none"
    return
  }

  projectWww.style.display = ""
  const hostname = sessionStore.get("hostname") || "localhost"
  projectWww.href = `http://${project}.${hostname}`
}

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

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