local nio = require("nio")
local git = {}

function git.commitFile(filepath)
  local function get_file_name(file)
    return vim.fn.fnamemodify(file, ":t:r")
  end

  local commitMessage = get_file_name(filepath) .. "-" .. os.date("%d_%B_%Y")

  os.execute('git add "' .. filepath .. '"')
  local commitCommand = 'git commit -m "' .. commitMessage .. '" &> /dev/null'
  local commitResult = os.execute(commitCommand)

  print("Commiting... " .. commitMessage)
  if commitResult == 256 then
    print("Nothing to commit")
    return
  elseif commitResult == 0 then
    print("Commit complete")
  else
    print("Unknown Error " .. commitResult)
    print(commitCommand)
    return
  end
end

function git.commitRest()
  local commitMessage = "Files changed since last commit-" .. os.date("%d_%B_%Y")
  os.execute("git add .")

  local commitCommand = 'git commit -m "' .. commitMessage .. '" &> /dev/null'
  local commitResult = os.execute(commitCommand)

  print("Commiting... " .. commitMessage)
  if commitResult == 256 then
    print("Nothing to commit")
    return
  elseif commitResult == 0 then
    print("Commit complete")
  else
    print("Unknown Error " .. commitResult)
    print(commitCommand)
    return
  end
end

function git.push()
  print("Pushing changes...")
  -- Push twice, in case the credentials expired. Ugly hack, but it works
  local pushSuccess = os.execute("git push &> /dev/null")
  if pushSuccess > 0 then
    os.execute("git push &> /dev/null")
  end

  print("Done")
end

function git.pull()
  nio.run(function()
    local pullProcess = nio.process.run({
      cmd = "git",
      args = { "pull", "--rebase", "--quiet", "--no-edit" },
    })

    local pullSuccess = pullProcess.result(true)
    if pullSuccess == 256 then
      vim.notify("Conflicts found. Please resolve and continue rebase", "error", {
        title = "Updating...",
      })
      return
    end

    vim.notify("Pull success", "info", {
      title = "Updating...",
    })
  end)
end

return git
