import injectService from 'ember-service/inject';
import ApplicationAdapter from './application';
import env from 'web-client/config/environment';

export default ApplicationAdapter.extend({
  tmiService: injectService('tmi'),

  shouldReloadRecord(store, snapshot) {
    let lastAccessedAt = snapshot.attr('lastAccessedAt');
    let now = new Date().getTime();
    let timeDiff = now - lastAccessedAt;
    let expiration = env.delay.expiration;

    return timeDiff > expiration;
  },

  shouldBackgroundReloadRecord() {
    return this.shouldReloadRecord(...arguments);
  },

  findRecord(store, type, id) {
    return this.request(`/api/channels/${id}/ember`);
  },

  findHasMany(store, snapshot, url) {
    return this.request(url);
  },

  query(store, type, params) {
    if (params.url) {
      return this.request(params.url);
    }

    return this._super(...arguments);
  },

  updateRecord(store, type, snapshot) {
    let data = {
      status: snapshot.record.get('status'),
      community: snapshot.record.get('community'),
      game: snapshot.record.get('game'),
      broadcaster_language: snapshot.record.get('broadcasterLanguage')
    };
    let record = snapshot.record;
    let updatedData;
    return this.request(`channels/${snapshot.id}`, 'put', { channel: data })
    .then(newData => {
      updatedData = newData;
      return this.get('tmiService.tmiSession');
    })
    .then(tmiSession => {
      return tmiSession.updateChannel(record.get('id'),
        { broadcaster_language_enabled: record.get('isLanguageRestricted') });
    })
    .then(() => {
      return updatedData;
    });
  }
});
