local M = {}

local function parent_dir(path)
  local idx = path:match('.*/()')
  if idx == nil then
    return nil
  end
  return path:sub(1, idx - 2)
end

local function scan_dir(path)
  local pfile = io.popen('ls -a "'..path..'"')
  local files = {}
  for filename in pfile:lines() do
    table.insert(files, filename)
  end
  return files
end

local rootfiles = {
  '.git',
  'package.json',
  'node_modules',
  'Makefile',
  '*.sln'
}

M.find_project_root = function()
  local stop_at = parent_dir(os.getenv('HOME'))
  local cwd = vim.fn.expand('%:p:h')
  local cur_dir = cwd
  while cur_dir:find(stop_at) == 1 do
    for _, filename in pairs(scan_dir(cur_dir)) do
      for _, rootfile in pairs(rootfiles) do
        if rootfile:sub(1, 1) == '*' then
          local idx = filename:find(rootfile:sub(2))
          if idx == filename:len() - rootfile:len() + 2 then
            return cur_dir
          end
        elseif filename == rootfile then
          print(cur_dir)
          return cur_dir
        end
      end
    end
    cur_dir = parent_dir(cur_dir)
  end
  return cwd
end

return M
