-- 1. Setup paths and capabilities
local status_ok, cmp_nvim_lsp = pcall(require, "cmp_nvim_lsp")
local capabilities = status_ok
    and cmp_nvim_lsp.default_capabilities(vim.lsp.protocol.make_client_capabilities())
    or vim.lsp.protocol.make_client_capabilities()
local java_bin = "java" -- use java from PATH
local jdtls_path = vim.fn.stdpath("data") .. "/mason/packages/jdtls"
local jdtls_launcher_jar = vim.fn.glob(jdtls_path .. "/plugins/org.eclipse.equinox.launcher_*.jar")
local lombok_jar = jdtls_path .. "/lombok.jar"

-- 2. Define the configuration
vim.lsp.config('jdtls', {
    cmd = {
        java_bin,
        "-Declipse.application=org.eclipse.jdt.ls.core.id1",
        "-Dosgi.bundles.defaultStartLevel=4",
        "-Declipse.product=org.eclipse.jdt.ls.core.product",
        "-Dlog.protocol=true",
        "-Dlog.level=INFO",
        "-Xmx2G",
        "-Xms256m",
        "--add-modules=ALL-SYSTEM",
        "--add-opens", "java.base/java.util=ALL-UNNAMED",
        "--add-opens", "java.base/java.lang=ALL-UNNAMED",
        "-javaagent:" .. lombok_jar,
        "-jar", jdtls_launcher_jar,
        "-configuration", jdtls_path .. "/config_linux",
        "-data", vim.fn.stdpath("data") .. "/jdtls-workspace/" .. vim.fn.fnamemodify(vim.fn.getcwd(), ":p:h:t"),
    },
    capabilities = capabilities,
    -- In 0.11, use root_markers instead of a root_dir function
    root_markers = { ".git", "mvnw", "gradlew", "pom.xml", "build.gradle" },
    settings = {
        java = {
            completion = {
                favoriteStaticMembers = {
                    "org.junit.jupiter.api.Assertions.*",
                    "org.mockito.Mockito.*",
                    "java.util.Objects.requireNonNull",
                    "java.util.Objects.requireNonNullElse",
                },
                filteredTypes = {
                    "com.sun.*",
                    "io.micrometer.shaded.*",
                    "java.awt.*",
                    "jdk.*",
                    "sun.*",
                },
            },
            import = {
                maven = { enabled = true, downloadSources = true },
                gradle = { enabled = true },
                settings = {
                    importOrder = { "java", "javax", "org", "com" },
                },
            },
            inlayHints = {
                parameterNames = { enabled = "all" },
            },
            format = {
                enabled = true,
            },
        },
    },
})

-- 3. Enable the server
vim.lsp.enable('jdtls')
