/* globals console */

import Ember from 'ember';
import ResourceCache from 'web-client/models/core/resource-cache';
import OwnerInjectionMixin from './owner-injection';

const { Mixin, Object: EmberObject } = Ember;

/**
 * Allows previously cached instances to be retrieved instead of creating a new instance. (Class Mixin)
 * @class
 */
export default Mixin.create(OwnerInjectionMixin, {
  find(findOptions) {
    let cache = this._getCache(),
        instance = cache.getResource(findOptions);

    if (!instance) {
      instance = this._create({_findOptions: findOptions});
      cache.setResource(findOptions, instance);
    }

    return instance;
  },

  /** This data resource cannot be instantiated with .create; Please use .find instead. */
  create() {
    console.warn('This data resource cannot be instantiated with .create; Please use .find instead.');
  },

  _getCache() {
    if (!this._cache) { this.resetCache(); }
    return this._cache;
  },

  resetCache() {
    this._cache = ResourceCache.create();
  },

  _create() {
    let instance = EmberObject.create.apply(this, [this._ownerInjection(), ...arguments]);
    if (instance.get('_findOptions.id')) {
      instance.set('id', instance.get('_findOptions.id'));
    }
    return instance;
  }
});
