-- Basic fzf search integration for xplr
-- Requires fzf (obviously), and bat for the preview

---@diagnostic disable
local xplr = xplr
---@diagnostic enable

local fzf = function()
    -- xplr.util.shell_execute doesn't work here since fzf needs an actual tty
    local p = io.popen("fzf --preview='bat --color=always {}'", "r")
    local output = p:read("*a")
    p:close()

    local lines = {}
    for line in output:gmatch("[^\r\n]+") do
        table.insert(lines, line)
    end

    local count = #lines

    if count == 0 then
        return
    else
        local path = lines[1]
        local msgs = { { FocusPath = path } }

        local isdir = xplr.util.shell_execute("test", { "-d", path }).returncode == 0
        if isdir then
            table.insert(msgs, "Enter")
        else
            table.insert(msgs, "PrintFocusPathAndQuit")
        end
        return msgs
    end
end

xplr.fn.custom.fzf = {}
xplr.fn.custom.fzf.search = function(_)
    return fzf()
end

xplr.config.modes.builtin.default.key_bindings.on_key["f"] = {
    help = "fzf search",
    messages = {
        "PopMode",
        { CallLua = "custom.fzf.search" }
    }
}
