local pickers = require("telescope.pickers")
local actions = require "telescope.actions"
local action_state = require "telescope.actions.state"
local finders = require("telescope.finders")
local conf = require("telescope.config").values

local wiki_utils = {}

local root_path = '/home/server/Workspace/DnD/Lumentis Campaign Setting'

local function get_title(file)
  for line in io.lines(file) do
    line = string.gsub(line, "#", "")
    line = string.gsub(line, "^%s*", "")
    line = string.gsub(line, "%s*$", "")
    return line
  end
end

-- our picker function: colors
local choose_link = function(opts, titles, links)
  opts = opts or {}
  pickers.new(opts, {
    prompt_title = "Choose a file",
    finder = finders.new_table {
      results = titles
    },
    sorter = conf.generic_sorter(opts),
    attach_mappings = function(prompt_bufnr, _)
        actions.select_default:replace(function()
            actions.close(prompt_bufnr)
            local selection = action_state.get_selected_entry()
            vim.api.nvim_put({ links[selection['index']] }, "", false, true)
        end)
        return true
    end,
  }):find()
end

function wiki_utils.insert_link()
    local scan = require("plenary.scandir").scan_dir(root_path)
    local titles = {}
    local links = {}
    for _, v in ipairs(scan) do
        if v:match("^.+(%..+)$") == ".md" then
            local absolute_filename = string.sub(v, root_path:len()+1, v:len())
            local title = get_title(v)
            if title:len() > 0 then
                local link = "[" .. title .. "](" .. absolute_filename .. ")"
                table.insert(titles, title)
                table.insert(links, link)
            end
        end
    end
    choose_link(require("telescope.themes").get_dropdown{}, titles, links)
end

vim.api.nvim_create_user_command("InsertWikiLink", wiki_utils.insert_link, {})
vim.keymap.set("n", "<leader>l", wiki_utils.insert_link, { noremap = true, silent = true })
vim.keymap.set("i", "<leader>l", wiki_utils.insert_link, { noremap = true, silent = true })

return wiki_utils
