/* globals _ */

import Mixin from 'ember-metal/mixin';
import Ember from 'ember';

const { $, Evented, on } = Ember;

export default Mixin.create(Evented, {
  /** overridden by individual models */
  hasRollbackBehavior: false,

  _initRollbackData: on('contentSet', function (data) {
    if (this.get('hasRollbackBehavior')) {
      this.set('rollbackData', $.extend(true, {}, data));
    }
  }),

  _updateRollbackData: on('saveSuccess', function (data) {
    if (this.get('hasRollbackBehavior')) {
      let self = this;

      _.each(data, function (value, key) {
        self.set(`rollbackData.${key}`, value);
      });
    }
  }),

  rollback: function () {
    if (this.get('hasRollbackBehavior')) {
      this.setProperties(
        $.extend(true, {}, this.get('rollbackData')) // deep copy
      );
    }
  }
});
