/* globals Twitch */

import Component from 'ember-component';
import computed from 'ember-computed';

const MAX_COMMUNITIES = 100;

export default Component.extend({
  communities: null,
  currentTag: null,

  lastVisitedCommunity: computed('communities.[]', 'currentTag.name', function () {
    let communities = this.get('communities');
    let communityLastVisited = Twitch.storage.get('communityLastVisited');
    if (communityLastVisited && communities.length && communityLastVisited !== this.get('currentTag.name')) {
      return communities.findBy('name', communityLastVisited);
    }
    return null;
  }),

  promotedCommunities: computed('communities.[]', 'currentTag.name', function () {
    let promotedCommunities = this.get('communities').filterBy('isPromoted');
    let currentTag = this.get('currentTag.name');
    if (currentTag) {
      promotedCommunities = promotedCommunities.rejectBy('name', currentTag);
    }
    return promotedCommunities;
  }),

  filteredCommunities: computed('lastVisitedCommunity', 'communities.[]', 'promotedCommunities.[]', 'currentTag.name', function () {
    let filteredCommunities = this.get('promotedCommunities').slice(0);
    let lastVisitedCommunity = this.get('lastVisitedCommunity');
    if (lastVisitedCommunity) {
      filteredCommunities.push(lastVisitedCommunity);
    }
    // Get all communities that are not already in the list
    let communities = this.get('communities')
      .reject(community => filteredCommunities.includes(community));
    // Ensure the currentTag is never displayed in this list
    let currentTag = this.get('currentTag.name');
    if (currentTag) {
      communities = communities.rejectBy('name', currentTag);
    }
    return filteredCommunities.concat(communities)
      .slice(0, MAX_COMMUNITIES);
  }),

  init() {
    this._super(...arguments);
    if (!this.get('communities')) {
      this.set('communities', []);
    }
  }
});
