local common = require('lsp.common')

function OrgImports(wait_ms)
  local params = vim.lsp.util.make_range_params()
  params.context = {only = {"source.organizeImports"}}
  local result = vim.lsp.buf_request_sync(0, "textDocument/codeAction", params, wait_ms)
  for _, res in pairs(result or {}) do
    for _, r in pairs(res.result or {}) do
      if r.edit then
        vim.lsp.util.apply_workspace_edit(r.edit, "utf-16")
      else
        vim.lsp.buf.execute_command(r.command)
      end
    end
  end
end

function format_with_imports(timeout_ms)
    OrgImports(1000)
    vim.lsp.buf.format()
end

vim.api.nvim_create_autocmd('BufWritePre', {
  pattern = '*.go',
  callback = function()
    vim.lsp.buf.code_action({ context = { only = { 'source.organizeImports' } }, apply = true })
    vim.lsp.buf.format()
  end
})

require('lspconfig').gopls.setup {
    capabilities = common.cap,
    on_attach = common.attach,
    flags = {
        debounce_text_changes = 150,
    },
    settings = {
        gopls = {
            gofumpt = true,
            usePlaceholders = true,
            completeUnimported = true,
            experimentalPostfixCompletions = true,
            analyses = {
                assign = true,
                atomic = true,
                atomicalign = true,
                bools = true,
                buildtag = true,
                composites = true,
                copylocks = true,
                erroras = true,
                fieldalignment = true,
                httpresponse = true,
                ifaceassert = true,
                infertypeargs = true,
                loopclosure = true,
                lostcancel = true,
                nilfunc = true,
                nilness = true,
                printf = true,
                shadow = true,
                simplifyrange = true,
                simplifyslice = true,
                sortslice = true,
                stdmethods = true,
                stringintconv = true,
                testinggoroutine = true,
                tests = true,
                unmarshal = true,
                unreachable = true,
                unsafeptr = true,
                unusedparams = true,
                unusedresult = true,
                unusedwrite = true,
                useany = true,
                nonewvars = true,
            },
        },
    },
}

-- Change local setting to separate 3rd-party and local imports with go.mod prefix
