import { module, test } from 'qunit';
import Ember from 'ember';
import LoadingMixin from 'web-client/models/core/mixins/instance/loading';

const { Object: EmberObject } = Ember;

module('LoadingMixin', {
  setup() {
    let Mock = {
      count: 0,
      deferred: $.Deferred(),
      get: function () {
        this.count++;
        return this.deferred;
      }
    };

    this.__apiLoadPromise = Mock.deferred;
    this.__getRequestCount = function () {
      return Mock.count;
    };

    this.mixin = EmberObject.extend(
      LoadingMixin, {
        apiLoad: function () {
          return Mock.get();
        }
      }
    );
  }
});

test('model is not loading or loaded before calling load', function (assert) {
  let resource = this.mixin.create({id: 1});
  assert.equal(resource.get('isLoaded'), false);
  assert.equal(resource.get('isLoading'), false);
});

test('model is loading immediately after calling load', function (assert) {
  let resource = this.mixin.create({id: 1});
  resource.load();
  assert.equal(resource.get('isLoading'), true);
  assert.equal(resource.get('isLoaded'), false);
});

test('model is loaded when the promise resolves', function (assert) {
  let resource = this.mixin.create({id: 1});
  resource.load();
  assert.equal(resource.get('isLoading'), true);
  assert.equal(resource.get('isLoaded'), false);
  this.__apiLoadPromise.resolve();
  assert.equal(resource.get('isLoading'), false);
  assert.equal(resource.get('isLoaded'), true);
});

test('loading the model twice does not make two api requests', function (assert) {
  let resource = this.mixin.create({id: 1});
  resource.load();
  this.__apiLoadPromise.resolve();
  assert.equal(resource.get('isLoaded'), true);
  resource.load();
  assert.equal(this.__getRequestCount(), 1);
});

test('model is immediately considered loaded and not loading if load is called after it is loaded', function (assert) {
  let resource = this.mixin.create({id: 1});
  resource.load();
  this.__apiLoadPromise.resolve();
  assert.equal(resource.get('isLoaded'), true);
  assert.equal(resource.get('isLoading'), false);
  resource.load();
  assert.equal(resource.get('isLoaded'), true);
  assert.equal(resource.get('isLoading'), false);
});
