import Mixin from 'ember-metal/mixin';
import Ember from 'ember';
import LoadingMixin from 'web-client/models/core/mixins/instance/loading';
import Model from 'web-client/models/core/model';
import KrakenListSerializer from 'web-client/models/core/serializers/kraken-list-serializer';
import computed from 'ember-computed';

const { on } = Ember;

export default Mixin.create(LoadingMixin, {
  _initializeContent: on('init', function () {
    this.set('content', []);
  }),

  /** Configuration */

  _initializeDefaultModel: on('init', function () {
    if (!this.get('model')) {
      this.set('model', Model);
    }
  }),

  /**
   * @override
   */
  serializer: KrakenListSerializer.create(),

  /** Publicly exposed properties and methods */

  itemSerializer: computed(function () {
    return (this.get('model')._create()).get('serializer');
  }),

  /**
   * @override
   */
  _setContent: function (rawContent) {
    let model = this.get('model'),
      itemSerializer = this.get('itemSerializer'),
      content = this.get('serializer').deserialize(rawContent);
    this.set('total', content.total);

    this.setObjects(content.items.map(function (item) {
      let instance = model.find({id: itemSerializer.deserialize(item).id});
      instance._loadSuccess(item);
      return instance;
    }));

    return content;
  }
});
