local function auto(event, opts)
  a.nvim_create_autocmd(event, opts)
end

local function augroup(name, opts)
  opts = opts or {}
  opts['clear'] = true
  a.nvim_create_augroup(name, opts)
end

local winchange = augroup('winchange')
local bufcheck = augroup('bufcheck')
local toggles = augroup('toggles')

auto({ "FocusGained", "TermClose", "TermLeave" }, {
  group = bufcheck,
  desc = 'Update contents of file.',
  command = "checktime",
})

auto("VimResized", {
  group = winchange,
  desc = 'Resize splits when window is resized.',
  callback = function()
    local current_tab = vim.fn.tabpagenr()
    vim.cmd("tabdo wincmd =")
    vim.cmd("tabnext " .. current_tab)
  end,
})

auto('TextYankPost', {
  group = bufcheck,
  pattern = '*',
  desc = 'Highlight on yank.',
  callback = function()
    vim.highlight.on_yank{ timeout = 250 }
  end
})

auto('BufRead', {
  pattern = '*',
  group = bufcheck,
  desc = 'Return to the last place the buffer was closed in.',
  callback = function() vim.cmd([[call setpos(".", getpos("'\""))]]) end
})

auto('FileType', {
  pattern = { 'gitcommit', 'markdown' },
  desc = 'Spell checking and wrapping in commit buffers and markdown files.',
  callback = function()
    vim.opt_local.wrap = true
    vim.opt_local.spell = true
  end
})

auto('BufWritePre', {
  pattern = '*',
  group = bufcheck,
  desc = 'Basically mkdir -p.',
  callback = function(ctx)
    if ctx.match:match("^%w%w+://") then return end
    local dir = vim.fn.fnamemodify(ctx.file, ':p:h')
    vim.fn.mkdir(dir, 'p')
  end
})

auto('WinLeave', {
	desc = 'Unset cursorline',
  group = toggles,
	callback = function() vim.opt.cursorline = false end
})

auto('WinEnter', {
	desc = 'Set cursorline',
  group = toggles,
	callback = function()
    if vim.bo.filetype ~= 'alpha' then
      vim.opt.cursorline = true
    end
  end
})

auto('ColorScheme', {
  desc = 'Update statusline on colorscheme change',
  group = winchange,
  callback = function() require('el').reset_windows() end
})