/* globals i18n */

import Controller from 'ember-controller';
import injectService from 'ember-service/inject';
import computed from 'ember-computed';
import limitForDirectoryTower from 'web-client/utilities/tower';
import { CHANNEL_PREVIEW_MIN_WIDTH } from 'web-client/services/layout';

const LANGUAGE_DIRECTORY_ROWCOUNT_DEFAULT = 2;

export default Controller.extend({
  globals: injectService(),
  broadcasterLanguages: computed.alias('globals.broadcasterLanguages'),

  layout: injectService(),
  browse: injectService(),
  experiments: injectService(),

  isBrowseExperimentEnabled: computed.readOnly('browse.isBrowseExperimentEnabled'),

  hideSection: false,
  isLoading: computed.alias('model.isLoading'),
  maxItems: null,

  init() {
    this._super(...arguments);

    this.get('experiments').getExperimentValue('LANGUAGE_DIRECTORY_ROWCOUNT_V2').then(value => {
      let rowCount = parseInt(value) || LANGUAGE_DIRECTORY_ROWCOUNT_DEFAULT;
      this.set('maxItems', limitForDirectoryTower({
          minWidth: CHANNEL_PREVIEW_MIN_WIDTH,
          rowCount: rowCount
        }));
      });
  },

  liveChannelText: computed('broadcasterLanguages', 'model.broadcaster_language', function () {
    let broadcasterLanguage = this.get('broadcasterLanguages')[this.get('model.broadcaster_language')];
    let translatedFormat = i18n("Channels in {{language}}");
    return translatedFormat.replace('{{language}}', broadcasterLanguage);
  }),

  hasChannels: computed.gt('model.length', 0),

  sampleChannels: computed('model.{length,isLoading}', 'maxItems', 'hasMoreStreams', function () {
    let sampleCount = this.get('maxItems');

    // Reserve a spot for "View All" button
    if (this.get('hasMoreChannels')) {
      sampleCount--;
    }

    return this.get('model.content').slice(0, sampleCount);
  }),

  hasMoreChannels: computed('content.length', 'maxItems', function () {
    return this.get('content.length') > this.get('maxItems');
  }),

  languageCode: computed('model', function () {
    return this.get('model').get('broadcaster_language');
  }),

  actions: {
    toggleHidden: function () {
      this.set('layout.hideLocalizedContentSection', !this.get('layout.hideLocalizedContentSection'));
    },

    loadMoreStreams: function () {
      let model = this.get('model');

      if (model) {
        model.loadMore();
      }
    }
  }
});
