       $.Deferred().resolve()
 
     __completeUpload: =>
-      # Update info until @apiPromise resolved.
+      # Update info until @apiDeferred resolved.
       timeout = 100
       do check = =>
-        if @apiPromise.state() == 'pending'
+        if @apiDeferred.state() == 'pending'
           @__updateInfo().done =>
             setTimeout check, timeout
             timeout += 50

      api # extended promise

    __notifyApi: ->
      @apiDeferred.notify @__progressInfo()

    __rejectApi: (err) =>
      @__progressState = 'error'
      @__notifyApi()
      @apiDeferred.reject err, @__fileInfo()

    __resolveApi: =>
      @__progressState = 'ready'
      @__notifyApi()
      @apiDeferred.resolve @__fileInfo()

    __initApi: ->
      @apiDeferred = $.Deferred()
      @apiPromise = @__extendApi @apiDeferred.promise()

      @__progressState = 'uploading'
      @__progress = 0
      @__notifyApi()

      @__uploadDf = $.Deferred()
        .done(@__completeUpload)
        .done =>
          @__progressState = 'uploaded'
          @__progress = 1
          @__notifyApi()
        .progress (progress) =>
          if progress > @__progress
            @__progress = progress
            @__notifyApi()
        .fail =>
          @__rejectApi('upload')

    promise: ->
      unless @__uploadStarted
        @__uploadStarted = true
        @__runValidators @__fileInfo()
        if @apiPromise.state() == 'pending'
          @__startUpload()
      @apiPromise


namespace 'uploadcare.utils', (utils) ->


    __cancel: =>
      @__rejectApi('user')

    __setupValidation: ->
      @validators = @settings.validators or @settings.__validators or []
