local json = require "json"
local lunacolors = require "lunacolors"

local M = {}

M.fmt = function(str, style)
    local styles = style:split(" ")
    local formatStr = ""
    for _, v in pairs(styles) do
        formatStr = formatStr .. "{" .. v .. "}"
    end
    formatStr = formatStr .. str
    return lunacolors.format(formatStr)
end

M.complete_func = function(query, ctx, fields)
    local carapace_arg = ctx

    -- If the ctx ends in a space, we need to append a "" to the carapace command
    if ctx:sub(-1, -1):match("%s") ~= nil then
        carapace_arg = carapace_arg .. '""'
    end

    -- Run carapace
    local carapace_cmd = "carapace " .. fields[1] .. " export " .. carapace_arg
    local res = io.popen(carapace_cmd)
    local out = res:read("*all")

    -- Extract completion items
    local out_table = json.decode(out)
    local values = {}

    if out_table["values"] ~= nil then
        for _, v in pairs(out_table["values"]) do
            -- Some completion items are styled; some aren't.
            if v["style"] ~= nil then
                if v["description"] ~= nil then
                    values[v["value"]] = { M.fmt(v["description"], v["style"]) }
                else
                    table.insert(values, v["value"])
                end
            else
                if v["description"] ~= nil then
                    values[v["value"]] = { v["description"] }
                else
                    table.insert(values, v["value"])
                end
            end
        end
    end

    -- Construct completion items table
    local comp = {
        {
            items = values,
            type = "list"
        }
    }

    return comp, query
end

return M
