-- This is part of LazyVim's code, with my modifications.
-- See: https://github.com/LazyVim/LazyVim/blob/main/lua/lazyvim/plugins/extras/formatting/prettier.lua

local util = require("formatter.util")
local defaults = require("formatter.defaults")

return {

	{
		"williamboman/mason.nvim",
		opts = function(_, opts)
			if type(opts.ensure_installed) == "table" then
				table.insert(opts.ensure_installed, "prettierd")
			end
		end,
	},

	{
		"mhartington/formatter.nvim",
		optional = true,
		keys = {
			{ "<Leader>ff", "<cmd>Format<CR>", desc = "Use Formatter" },
		},
		opts = function(_, opts)
			opts = opts or {}
			local filetypes = {
				-- NOTE: If using this config, you need to install prettierd.
				-- At the time of writing that is done with:
				-- `sudo npm install -g @fsouza/prettierd`
				["*"] = {
					-- NOTE: This is not a fallback! It seems to overwrite any other
					-- configs.
					require("formatter.filetypes.any").remove_trailing_whitespace,
				},
				text = { require("formatter.defaults.prettierd") },
				rust = {
					rustfmt = function()
						return {
							exe = "rustfmt",
							args = { "--emit=std	ut" },
							stdin = true,
						}
					end,
				},
				cpp = { require("formatter.filetypes.cpp").clangformat },
				css = { require("formatter.filetypes.css").prettierd },
				html = { require("formatter.filetypes.html").prettierd },
				htmldjango = {
					function()
						return {
							exe = "djlint",
							args = { "-", "--reformat" },
							stdin = 1,
						}
					end,
				},
				java = { require("formatter.filetypes.java").clangformat() },
				javascript = { require("formatter.filetypes.javascript").prettierd },
				json = { require("formatter.filetypes.json").prettierd },
				cmake = { require("formatter.filetypes.cmake") },
				latex = { require("formatter.filetypes.latex").latexindent },
				markdown = { require("formatter.filetypes.markdown").prettierd },
				php = { require("formatter.filetypes.php").phpcbf },
				python = {
					function()
						return {
							exe = "autopep8",
							args = { "--aggressive -" },
							stdin = 1,
						}
					end,
				},
				sh = { require("formatter.filetypes.sh").shfmt() },
				sql = { require("formatter.filetypes.sql").pgformat() },
				toml = { require("formatter.filetypes.toml").taplo() },
				go = { require("formatter.filetypes.go").gofmt() },
				yaml = { require("formatter.filetypes.yaml").prettierd },
				c = { require("formatter.filetypes.c").clangformat },
			}
			opts.filetype = vim.tbl_extend("keep", opts.filetype or {}, filetypes)
		end,
	},

	{
		"jose-elias-alvarez/null-ls.nvim",
		optional = true,
		opts = function(_, opts)
			local nls = require("null-ls")
			table.insert(opts.sources, nls.builtins.formatting.prettierd)
		end,
	},
}
