import Service from 'ember-service';
import Ember from 'ember';

const { inject } = Ember;
const MAX_LENGTH = 50;

export default Service.extend({
  store: inject.service(),

  _maxLength: MAX_LENGTH,

  _createRecord(store, channel, timestamp) {
    return store.createRecord('watched-channel', {
      id: channel,
      timestamp: timestamp
    });
  },

  _channelNotFound(store, channel, timestamp, watchedChannels) {
    let length = watchedChannels.get('length');

    if (length < this.get('_maxLength')) {
      return this._createRecord(store, channel, timestamp).save();
    }
    let oldestChannel = watchedChannels.sortBy('timestamp').get('firstObject');

    oldestChannel.deleteRecord();
    return oldestChannel.save().then(() => {
      return this._createRecord(store, channel, timestamp).save();
    });
  },

  addChannel(channel) {
    let store = this.get('store');
    let timestamp = new Date();

    return store.findAll('watched-channel').then((watchedChannels) => {
      let watchedChannel = watchedChannels.findBy('id', channel);

      if (watchedChannel) {
        watchedChannel.set('timestamp', timestamp);
        return watchedChannel.save();
      }
      return this._channelNotFound(store, channel, timestamp, watchedChannels);
    });
  }
});
