local plug_dir = vim.fn.stdpath('config') .. '/lua'
local M = {}

function M.packer_compile()
    local file = vim.fn.expand('%:p')
    if file:match(plug_dir) then
        vim.api.nvim_command('source <afile> | PackerCompile')
    end
end

function M.nvim_create_augroups(definitions)
    for group_name, definition in pairs(definitions) do
        vim.api.nvim_command('augroup ' .. group_name)
        vim.api.nvim_command('autocmd!')
        for _, def in ipairs(definition) do
            local command = table.concat(vim.tbl_flatten{'autocmd', def}, ' ')
            vim.api.nvim_command(command)
        end
        vim.api.nvim_command('augroup END')
    end
end

function M.load_autocmds()
    local definitions = {
        plugins = {
            -- Wrap lines in preview window
            -- {"User TelescopePreviewerLoaded", [[setlocal wrap]]},
            -- Re-compile packer on config changed
            {"BufWritePost", "*.lua", "lua require('events').packer_compile()"},
            -- Register binding for ToggleTerm inside term mode
            {"TermEnter", "term://*toggleterm#*", "tnoremap <silent><C-\\> <C-\\><C-n>:ToggleTerm<CR>"}
        },

        -- Edit binary files in hex with xxd (:%!xxd and :%!xxd -r)
        -- or using nvim -b to edit files using xxd-format
        binary = {
            {"BufReadPre"  , "*.bin,*.exe", "let &bin=1"},
            {"BufReadPost" , "*.bin,*.exe", "if &bin | %!xxd"},
            {"BufReadPost" , "*.bin,*.exe", "set ft=xxd | endif"},
            {"BufWritePre" , "*.bin,*.exe", "if &bin | %!xxd -r"},
            {"BufWritePre" , "*.bin,*.exe", "endif"},
            {"BufWritePost", "*.bin,*.exe", "if &bin | %!xxd"},
            {"BufWritePost", "*.bin,*.exe", "set nomod | endif"}
        },

        buf = {
            -- Auto-spelling in doc files
            {"BufNewFile,BufRead", "*.md,*.mkd", "setlocal spell"},
            {"BufNewFile,BufRead", "*.tex", "setlocal spell"},
            -- Auto-hide numbers, statusline in specific buffers
            -- {"BufEnter", "term://*", "setlocal norelativenumber nonumber"},
            -- {"BufEnter", "term://*", "set laststatus=0"},
            {"BufEnter,BufWinEnter,WinEnter,CmdwinEnter", "*", [[if bufname('%') == "NvimTree" | set laststatus=0 | else | set laststatus=2 | endif]]}
        },

        wins = {
            -- Equalize window dimensions when resizing vim window
            {"VimResized", "*", [[tabdo wincmd =]]},
            -- Force writing shada on leaving nvim
            {"VimLeave", "*", [[if has('nvim') | wshada! | else | wviminfo! | endif]]},
            -- Check if file changed when its window is focus, more eager than 'autoread'
            {"FocusGained", "* checktime"}
        },

        ft = {
            {"FileType", "dashboard", "set showtabline=0 | autocmd WinLeave <buffer> set showtabline=2"},
            {"BufNewFile,BufRead", "*.md,*.mkd", "setfiletype markdown"},
            {"BufNewFile,BufRead", "*.toml", "setfiletype toml"},
            {"BufNewFile,BufRead", "*.tex", "setfiletype tex"},
            {"BufNewFile,BufRead", "*.conf", "setfiletype cfg"},
            {"BufNewFile,BufRead", "*.rasi", "setfiletype css"},
            {"BufNewFile,BufRead", "vifmrc,*.vifm", "setfiletype vim"},
            {"BufNewFile,BufRead", "*.log,*_log,*.LO,G*_LOG", "setfiletype log"}
        },

        yank = {
            {"TextYankPost", [[* silent! lua vim.highlight.on_yank({higroup="IncSearch", timeout=300})]]}
        }
    }

    M.nvim_create_augroups(definitions)
end

return M
