local fn, api = vim.fn, vim.api

-- Require since we use 'packer' as opt
api.nvim_command('packadd packer.nvim')
local present, packer = pcall(require, 'packer')

if not present then
    local packer_dir = fn.stdpath('data') .. '/site/pack/packer/opt/packer.nvim'

    vim.notify('Cloning packer ...', vim.log.levels.INFO)
    -- remove packer_dir before cloning
    fn.delete(packer_dir, 'rf')
    fn.system {'git', 'clone', 'https://github.com/wbthomason/packer.nvim', packer_dir}
    api.nvim_command('packadd packer.nvim')
    present, packer = pcall(require, 'packer')

    if present then
        vim.notify('Pakcer cloned successfully.', vim.log.levels.INFO)
    else
        vim.notify('Git clone error for packer!', vim.log.levels.ERROR)
    end
end

local util = require('packer.util')

packer.init {
    compile_path = util.join_paths(fn.stdpath('data'), 'site', 'plugin', 'packer_compiled.lua'),
    auto_clean = true,
    compile_on_sync = true,
    auto_reload_compiled = true,
    git = {
        -- default_url_format = 'https://github.com/%s',
        clone_timeout = 120
    },
    display = {
        -- open_fn = function()
        --     return util.float {border = 'single'}
        -- end,
        open_cmd = '60vnew \\[packer\\]',
        working_sym = '⟳',
        error_sym = '✗',
        done_sym = '✓',
        removed_sym = '-',
        moved_sym = '→',
        header_sym = '━',
        show_all_info = true,
        prompt_boder = 'single'
    },
    -- profile = {enable = true, threshold = 1},
    luarocks = {python_cmd = 'python3'}
}

-- Re-compile packer on config changed
_G.packer_compile_on_save = function()
    local file = fn.expand('%:p')
    local filename = fn.expand('%:p:t')
    local config_dir = fn.stdpath('config') .. '/lua/modules'

    if file:match(config_dir) and filename ~= 'pack.lua' then
        vim.api.nvim_command('source <afile> | PackerCompile')
    end
end
api.nvim_command('autocmd BufWritePost *.lua lua packer_compile_on_save()')

return packer
