import Ember from 'ember';
import StoreModel from 'web-client/models/store';
import logApiFailure from 'web-client/utilities/log-api-failure';

const { inject } = Ember;

const PanelModel = StoreModel.defineModel({
  api: inject.service(),

  deserialize (data) {
    data.id = data._id;

    if (data.data && data.data.end_date) {
      // Seems like we shouldn't have to add the timezone offset here. Looks like a bug in date.js string parsing
      data.data.end_date = Date.parse(data.data.end_date).add(-(new Date()).getTimezoneOffset()).minutes();
    }

    return data;
  },

  saveRemote(data) {
    return this.get('api')
      .request('put', `/api/channels/${data.channel}/panels/${data.id}`, data);
  }
});

PanelModel.defineCollection('user', {
  api: inject.service(),

  request() {
    return this.get('api').request('get', `/api/channels/${this.get('user')}/panels`);
  },

  afterSuccess(response) {
    this.setContent(response);
  },

  afterFail() {
    logApiFailure('panels');
  }
});

export default PanelModel;
