-- Check Lspconfig.
local status_lspconfig, lspconfig = pcall(require, 'lspconfig')
if (not status_lspconfig) then return end

-- Check Mason.
local status_mason, mason = pcall(require, 'mason')
if (not status_mason) then return end

-- Check Mason lsp installer.
local status_mason_lspconfig, mason_lspconfig = pcall(require, 'mason-lspconfig')
if (not status_mason_lspconfig) then return end

-- Config servers.
local servers = {
	'lua_ls',
	'bashls',
	'clangd',
	'cmake',
	'html',
	'tsserver',
	'volar',
	'dockerls',
	'jsonls',
	'yamlls',
	'graphql'
}

--  This function gets run when an LSP connects to a particular buffer.
local on_attach = function(_, bufnr)
	vim.keymap.set('n', '<leader>rn', vim.lsp.buf.rename)
	vim.keymap.set('n', '<leader>ca', vim.lsp.buf.code_action)

	-- LSP functionality
	vim.keymap.set('n', 'gd', vim.lsp.buf.definition)
	vim.keymap.set('n', 'gy', vim.lsp.buf.type_definition)
	vim.keymap.set('n', 'gi', vim.lsp.buf.implementation)
	vim.keymap.set('n', 'gD', vim.lsp.buf.declaration)
	vim.keymap.set('n', 'K', vim.lsp.buf.hover)
	vim.keymap.set('n', '<C-k>', vim.lsp.buf.signature_help)
end

-- nvim-cmp supports additional completion capabilities, so broadcast that to servers
local capabilities = vim.lsp.protocol.make_client_capabilities()
capabilities = require('cmp_nvim_lsp').default_capabilities(capabilities)

-- Mason.
mason.setup {}

-- Mason lsp installer.
mason_lspconfig.setup {
	ensure_installed = servers,
}

-- Mason configure servers.
mason_lspconfig.setup_handlers {
	function(server_name)

		local config = {
			on_attach = on_attach,
			capabilities = capabilities,
			settings = {}
		}

		-- LUA.
		if server_name == 'lua_ls' then
			config.settings = {
				Lua = {
					diagnostics = {
						globals = { 'vim' }
					},
					workspace = {
						library = vim.api.nvim_get_runtime_file('', true),
						checkThirdParty = false
					}
				}
			}
			lspconfig[server_name].setup(config)
		end

		-- TSSERVER.
		if server_name == 'tsserver' then
			config.init_options = {
				plugins = {
					{
						name = '@vue/typescript-plugin',
						location = '/home/antoxa/.nvm/versions/node/v20.12.0/lib/node_modules/@vue/typescript-plugin',
						languages = { 'javascript', 'typescript', 'vue' },
					},
				},
			}
			config.filetypes = {
				'javascript',
				'typescript',
				'vue',
			}
		end

		-- GRAPHQL.
		if server_name == 'graphql' then
			config.filetypes = { 'graphql' }
		end

		lspconfig[server_name].setup(config)
	end
}
