--[[--
TODO: rust-tools.nvim, crates.nvim, go.nvim, clojure-vim/*,
nvim-revJ.lua, fcitx.nvim, pandoc.nvim, qf_helper.nvim,
tldr.nvim, refactoring.nvim, git-worktree.nvim, nvim-regexplainer
--]]

local fn, cmd = vim.fn, vim.api.nvim_command
local compile_path = fn.stdpath('data') .. '/site/plugin/packer_compiled.lua'
local snapshot_path = fn.stdpath('cache') .. '/packer.nvim'
local modules_dir = fn.stdpath('config') .. '/lua/user/modules'
local packer = nil
local M = {}

local function bootstrap_packer()
    local packer_dir = fn.stdpath('data') .. '/site/pack/packer/opt/packer.nvim'
    if fn.empty(fn.glob(packer_dir)) > 0 then
        vim.notify('Cloning packer.nvim ...', vim.log.levels.INFO)
        fn.system { 'git', 'clone', '--depth', '1', 'https://github.com/wbthomason/packer.nvim', packer_dir }
        vim.notify('packer.nvim is cloned successfully.', vim.log.levels.INFO)
    end
end

local function get_plugins_list()
    local list = {}
    local tmp = vim.split(fn.globpath(modules_dir, '*/plugins.lua'), '\n')
    for _, f in ipairs(tmp) do
        list[#list + 1] = f:sub(#modules_dir - 11, -1)
    end
    return list
end

local function load_plugins()
    if not packer then
        cmd('packadd packer.nvim')
        packer = require('packer')
    end

    local util = require('packer.util')
    packer.init {
        compile_path = compile_path,
        snapshot_path = snapshot_path,
        disable_commands = true,
        auto_clean = true,
        compile_on_sync = true,
        auto_reload_compiled = true,
        git = { depth = 1, clone_timeout = 120 },
        display = {
            open_fn = function()
                return util.float { border = vim.g.border_style }
            end,
            -- open_cmd = '60vnew \\[packer\\]',
            working_sym = '⟳',
            error_sym = '✗',
            done_sym = '✓',
            removed_sym = '-',
            moved_sym = '→',
            header_sym = '━',
            show_all_info = true,
            prompt_border = vim.g.border_style,
        },
        -- profile = { enable = true, threshold = 1 },
        luarocks = { python_cmd = 'python3' },
    }

    -- This is recommended when using `luafile <afile>` a lot
    packer.reset()

    -- Configure plugins
    local use = packer.use
    local repos = {}
    local plugins_file = get_plugins_list()
    for _, m in ipairs(plugins_file) do
        local local_repos = require(m:sub(0, #m - 4))
        for repo, conf in pairs(local_repos) do
            repos[#repos + 1] = vim.tbl_extend('force', { repo }, conf)
        end
    end
    for _, repo in ipairs(repos) do
        use(repo)
    end
end

function M.ensure_plugins()
    bootstrap_packer()
    load_plugins()
    packer.install() -- Install plugins if missing
end

-- function M.compile_on_save()
--     local file = fn.expand('%:p')
--     if file:match(modules_dir) then
--         packer.clean()
--         packer.compile(compile_path)
--     end
-- end

function M.on_compile_done()
    fn.system { '/usr/bin/luajit', '-bg', compile_path, compile_path }
    vim.notify('packer.compile: Complete', vim.log.levels.DEBUG, { title = 'packer.nvim' })
end

function M.make_commands()
    -- Don't define PackerInstall, PackerUpdate and PackerProfile
    vim.api.nvim_exec(
        [[
    command! -nargs=+ -complete=customlist,v:lua.require'packer.snapshot'.completion.create PackerSnapshot lua require('packer').snapshot(<f-args>)
    command! -nargs=+ -complete=customlist,v:lua.require'packer.snapshot'.completion.rollback PackerSnapshotRollback lua require('packer').rollback(<f-args>)
    command! -nargs=+ -complete=customlist,v:lua.require'packer.snapshot'.completion.snapshot PackerSnapshotDelete lua require('packer.snapshot').delete(<f-args>)
    command! -nargs=* -complete=customlist,v:lua.require'packer'.plugin_complete PackerSync lua require('packer').sync(<f-args>)
    command! PackerClean             lua require('packer').clean()
    command! -nargs=* PackerCompile  lua require('packer').compile(<q-args>)
    command! PackerStatus            lua require('packer').status()
    command! -bang -nargs=+ -complete=customlist,v:lua.require'packer'.loader_complete PackerLoad lua require('packer').loader(<f-args>, '<bang>' == '!')
    ]],
        false
    )
end

return M
