import Model from 'ember-data/model';
import attr from 'ember-data/attr';
import { belongsTo } from 'ember-data/relationships';
import computed from 'ember-computed';

/**
 * This model represents a file upload for its parent uploader-video model.
 *
 * The model is initialized with a token, id, and URL from the server's
 * response on uploader-video creation.
 *
 * Calling videoUpload.save() will begin the file upload, handling multiple
 * requests to the server. The promise will finally resolve when the upload has
 * been successfully completed.
 *
 * During the upload, the adapter sends updates to this model via the `onUploadProgress`
 * and `didComplete` callbacks. This allows Ember's observation system to track `total`,
 * `loaded`, and `isComplete` properties.
 */
export default Model.extend({
  file: attr(),
  video: belongsTo('manager/uploader-video'),
  token: attr('string'),
  url: attr('string'),
  loaded: 0,
  isUploading: false,
  isComplete: false,

  // When an upload is in progress, this property will hold a callback that can
  // be used to abort the request.
  xhrAbort: null,

  abort() {
    let xhrAbort = this.get('xhrAbort');

    if (xhrAbort) {
      xhrAbort();
    }
  },

  isSuccess: computed('isComplete', 'isError', function() {
    return this.get('isComplete') && !this.get('isError');
  }),

  total: computed('file', function() {
    return this.get('file.size') || 0;
  }),

  // Called when the adapter begins sending requests to upload this file.
  onUploadStart() {
    this.set('isUploading', true);
  },

  // Called when the XHR request receives the onprogress event.
  onUploadProgress({ loaded }) {
    this.set('loaded', loaded);
  },

  // Called when the XHR request finishes.
  didComplete() {
    this.set('isUploading', false);
    this.set('isComplete', true);
  }
});
