import { moduleForModel, test } from 'ember-qunit';
import run from 'ember-runloop';

moduleForModel('search', 'Unit | Serializer | search', {
  integration: true,

  beforeEach() {
    this.serializer = this.store().serializerFor('search');
  }
});

test('serializing a single query response', function(assert) {
  let payload = {
    "results": [{
      "nbHits": 100,
      "page": 0,
      "hitsPerPage": 2,
      "index": "game",
      "hits": [{
        "name": "Call of Duty: Black Ops III"
      }, {
        "name": "Dark Souls III"
      }]
    }]
  };

  let model;
  run(() => {
    this.serializer.pushPayload(this.store(), payload);
    model = this.store().peekRecord('search', 'game');
  });

  assert.equal(model.get('totalHitCount'), 100, 'uses 0 hitsPerPage result for totalHitCount');
  assert.equal(model.get('hits').length, 2, 'has hits');
  assert.equal(model.get('page'), 0, 'stores the current page');
});

test('serializing a response with a totalHitCount query', function(assert) {
  let payload = {
    "results": [{
      "nbHits": 40000,
      "page": 0,
      "hitsPerPage": 50,
      "index": "game",
      "hits": [{
        "name": "Call of Duty: Black Ops III"
      }, {
        "name": "Dark Souls III"
      }]
    }, {
      "nbHits": 60000,
      "page": 0,
      "hitsPerPage": 0,
      "index": "game",
      "hits": []
    }]
  };

  let model;
  run(() => {
    this.serializer.pushPayload(this.store(), payload);
    model = this.store().peekRecord('search', 'game');
  });

  assert.equal(model.get('totalHitCount'), 60000, 'uses 0 hitsPerPage result for totalHitCount');
  assert.equal(model.get('hits').length, 2, 'has hits');
  assert.equal(model.get('page'), 0, 'stores the current page');
});

test('serializing an additional page of results', function(assert) {
  let firstPayload = {
    "results": [{
      "nbHits": 40000,
      "page": 0,
      "hitsPerPage": 2,
      "index": "game",
      "hits": [{
        "name": "Game 1"
      }, {
        "name": "Game 2"
      }]
    }]
  };

  let model;
  run(() => {
    this.serializer.pushPayload(this.store(), firstPayload);
    model = this.store().peekRecord('search', 'game');
  });

  let secondPayload = {
    "results": [{
      "nbHits": 40000,
      "page": 1,
      "hitsPerPage": 2,
      "index": "game",
      "hits": [{
        "name": "Game 3"
      }, {
        "name": "Game 4"
      }]
    }]
  };

  run(() => {
    this.serializer.pushPayload(this.store(), secondPayload);
  });

  let hitNames = model.get('hits').mapBy('name');
  assert.deepEqual(hitNames, ['Game 1', 'Game 2', 'Game 3', 'Game 4'], 'stores the cummulative hits');
  assert.equal(model.get('page'), 1, 'updates the current page');
});
