import injectService from 'ember-service/inject';
import Helper from 'ember-helper';

export default Helper.extend({
  feeds: injectService(),

  init() {
    this._super(...arguments);
    this._value = null;
    this._lastChannelName = null;
  },

  compute([channelName]) {
    if (this._value && this._lastChannelName === channelName) {
      return this._value;
    }

    let feeds = this.get('feeds');
    this._lastChannelName = channelName;
    feeds.getFeedForUser(channelName).then(() => {
      if (this.isDestroyed || this._lastChannelName !== channelName) { return; }
      this._value = {isOptedIntoChannelFeed: true};
      this.recompute();
    }, error => {
      if (this.isDestroyed || this._lastChannelName !== channelName) { return; }
      this._value = {isOptedIntoChannelFeed: false};
      this.recompute();

      if (error.status === 403) {
        return;
      }
      throw error;
    });

    return null;
  }
});
