       @interval = setTimeout bind, 0
 
     stopWatching: ->
-      clearTimeout @interval if @interval
+      if @interval
+        clearTimeout @interval
       @interval = null
 
     __updateStatus: ->
-      utils.jsonp("#{@settings.urlBase}/status/", {@token})
+      utils.jsonp(@poolUrl, {@token})
         .fail (error) =>
           @stopWatching()
-          @uploader.__state 'error'
+          $(this).trigger 'error'
         .done (data) =>
-          @uploader.__state data.status, data if data.status in ['progress', 'success', 'error']
+          $(this).trigger data.status, data

        .fail (error) =>
          if @settings.autostore && /autostore/i.test(error)
            utils.commonWarning('autostore')
          @__state('error')
        .done (data) =>
          @__token = data.token
          @__pollWatcher.watch @__token
          @__pusherWatcher.watch @__token
          $(@__pusherWatcher).on 'started', =>
            @__pollWatcher.stopWatching()

      @__uploadDf.always =>
        @__shutdown = true
        @__pusherWatcher.stopWatching()
        @__pollWatcher.stopWatching()


    ####### Four States of uploader
    __state: (state, data) ->
      (
        start: =>
          @__shutdown = false

        progress: (data) =>
          if @__shutdown
            return
          @fileSize = data.total
          @__uploadDf.notify(data.done / data.total)

        success: (data) =>
          if @__shutdown
            return
          @__state('progress', data)
          [@fileName, @fileId] = [data.original_filename, data.uuid]
          @__uploadDf.resolve()

        error: =>
          @__uploadDf.reject()
      )[state](data)


  class PusherWatcher
    constructor: (@uploader, @settings) ->
      @pusher = pusher.getPusher(@settings.pusherKey, 'url-upload')

    watch: (@token) ->
      @channel = @pusher.subscribe("task-status-#{@token}")

      onStarted = =>
        $(this).trigger 'started'
        @channel.unbind ev, onStarted for ev in ['progress', 'success']

      for ev in ['progress', 'success']
        do (ev) =>
          @channel.bind ev, (data) => @uploader.__state ev, data
          @channel.bind ev, onStarted  # self-removed callback should be last!

      @channel.bind 'fail', (data) => @uploader.__state('error')

    stopWatching: ->
      @pusher.release() if @pusher
      @pusher = null

  class PollWatcher
    constructor: (@uploader, @settings) ->

    watch: (@token) ->
      bind = =>

namespace 'uploadcare.files', (ns) ->

  class ns.UrlFile extends ns.BaseFile
    allEvents: 'progress success error fail'

    constructor: (settings, @__url) ->
      super

      filename = utils.splitUrlRegex.exec(@__url)[3].split('/').pop()
      if filename
