 namespace 'uploadcare.files', (ns) ->
 
   class ns.UrlFile extends ns.BaseFile
+    allEvents: 'progress success error fail'
+
     constructor: (settings, @__url) ->
       super
-      @__shutdown = true
 
       filename = utils.splitUrlRegex.exec(@__url)[3].split('/').pop()
       if filename

      @__notifyApi()

    __startUpload: ->

      @__pollWatcher = new PollWatcher(this, @settings)
      @__pusherWatcher = new PusherWatcher(this, @settings)

      @__state('start')

      data =
        pub_key: @settings.publicKey

        .fail (error) =>
          if @settings.autostore && /autostore/i.test(error)
            utils.commonWarning('autostore')
          @__uploadDf.reject()
        .done (data) =>
          pusherWatcher.watch data.token
          pollWatcher.watch data.token

      @__uploadDf.always =>
        $([pusherWatcher, pollWatcher]).off(@allEvents)
        pusherWatcher.stopWatching()
        pollWatcher.stopWatching()

    __listenWatcher: (watcher) =>
      watcher
        .on 'progress', (e, data) =>
          @fileSize = data.total
          @__uploadDf.notify(data.done / data.total)

        .on 'success', (e, data) =>
          $(e.target).trigger('progress', data)
          @fileId = data.uuid
          @fileName = data.original_filename
          @__uploadDf.resolve()

        .on 'error fail', @__uploadDf.reject


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

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

      channel.bind_all (ev, data) =>
        $(this).trigger ev, data

    stopWatching: ->
      @pusher.release()


  class PollWatcher
    constructor: (@poolUrl) ->

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