 Git = require 'nodegit'
+ChildProcess = require 'child_process'
 
 normalizeOptions = (options, Ctor) ->
   instance = (if options instanceof Ctor then options else new Ctor())

  changes: {}

  constructor: ->
    @repoPromise = Git.Repository.open(atom.project.getPaths()[0])
    @indexPromise = @repoPromise.then (repo) ->
      repo.openIndex()


      repo.getStatus()

  stagePath: (path) ->
    @stageAllPaths([path])

  stageAllPaths: (paths) ->
    @indexPromise.then (index) ->
      index.addByPath(path) for path in paths
      index.write()
      new Promise (resolve, reject) =>
        process.nextTick =>
          resolve()

  unstagePath: (path) ->
    @unstageAllPaths([path])

  unstageAllPaths: (paths) ->
    new Promise (resolve, reject) =>
      if paths.length
        ChildProcess.execSync "git reset HEAD #{paths.join(' ')}",
          cwd: @repoPath

      process.nextTick => resolve()

  commit: (message) ->
    @repoPromise.then (repo) =>
      @indexPromise.then (index) =>
        index.writeTree().then (indexTree) =>
          repo.getHeadCommit().then (parent) =>
            author = Git.Signature.default(repo)
            return repo.createCommit("HEAD", author, author, message, indexTree, [parent])
