-- Starship.rs support for Hilbish
-- Supports the following features:
-- * exit codes
-- * command duration (kind of - it usually works but is not 100% perfect)
-- * number of jobs
-- * continuation prompt (which some shells like fish don't even support!)
-- * anything else inherently handled by starship (git, username, etc)

local bait = require 'bait'
local hilbish = require 'hilbish'

local M = {}

M.execTime = {}

function M.doPrompt(status, num_jobs, num_secs)
	-- Since lua by default only has second-resolution with its os.time() function,
	-- we need to multiply by 1000 to get milliseconds elapsed.
	-- This, of course, means we don't actually get millisecond-level resolution, but whatever - we work with what we got.
	local time_ms = num_secs * 1000

	local cmd = "starship prompt --status " .. status .. " --jobs " .. num_jobs .. " --cmd-duration " .. time_ms
	local res = io.popen(cmd)
	hilbish.prompt(res:read("*all"))
end

function M.doCommandExit(code, cmdStr)
	local cur_time = os.time()
	local time_elapsed = 0

	if cmdStr ~= nil then
		if M.execTime[cmdStr] ~= nil then
			time_elapsed = cur_time - M.execTime[cmdStr]
		end
    	M.execTime[cmdStr] = nil
	end

	local jobs = hilbish.jobs.all()
	M.doPrompt(code, #jobs, time_elapsed)
end

function M.doCommandPreExec(input)
    if input ~= nil then
		M.execTime[input] = os.time()
	end
end

function M.setup()
	local cmd = "starship prompt --continuation"
	local res = io.popen(cmd)
	hilbish.multiprompt(res:read("*all"))

	M.doPrompt(0, 0, 0)

	bait.catch("command.preexec", function(input, _)
		M.doCommandPreExec(input)
    end)

	bait.catch('command.exit', function(code, cmdStr)
		M.doCommandExit(code, cmdStr)
	end)
end

return M
