import moment from 'moment';
import Transform from 'ember-data/transform';

// This transform supports parsing RFC3339 nanosecond precision timestamps (ex. "2017-01-05T09:21:38.814511652Z").
//
// This exists because in kraken v5 APIs, the date strings are returned with nanosecond precision, and
// `Date.parse` and `Ember.Date.parse` both fail to parse. `Date.parse` is overwritten by datejs, though native
// `Date.parse` should work on RFC3339 nanosecond precision timestamps.
//
// Based off https://github.com/emberjs/data/blob/v2.10.0/addon/-private/transforms/date.js
export default Transform.extend({
  // The nanosecond precision is lost
  deserialize: function(serialized) {
    if (serialized === null || serialized === undefined) {
      return null;
    }

    return moment(serialized).toDate();
  },

  serialize: function(deserialized) {
    if (deserialized instanceof Date && !isNaN(deserialized)) {
      return deserialized.toISOString();
    }

    return null;
  }
});
