import Mixin from 'ember-metal/mixin';
import computed from 'ember-computed';
import injectService from 'ember-service/inject';
import {
  ALL_VIDEOS_PARAM,
  UPLOAD_TYPE_PARAM,
  ARCHIVE_TYPE_PARAM,
  HIGHLIGHT_TYPE_PARAM
} from 'web-client/utilities/video/types';
import {
  SORT_VIEWS_TYPE,
  SORT_TIME_TYPE
} from 'web-client/utilities/video/sorts';
import { videoSortLabel } from 'web-client/helpers/video-sort-label';
import DeprecatedVideo from 'web-client/models/deprecated-video';

export const PAST_BROADCASTS_TYPE = 'past-broadcasts';
export const HIGHLIGHTS_TYPE = 'highlights';
export const UPLOADED_VIDEOS_TYPE = 'uploads';
export const ALL_VIDEOS_TYPE =  'all';
export const UPLOAD_PERIOD_PARAM = 'month';

export const TYPE_PARAM_MAP = {
  [ALL_VIDEOS_TYPE]: ALL_VIDEOS_PARAM,
  [UPLOADED_VIDEOS_TYPE]: UPLOAD_TYPE_PARAM,
  [PAST_BROADCASTS_TYPE]: ARCHIVE_TYPE_PARAM,
  [HIGHLIGHTS_TYPE]: HIGHLIGHT_TYPE_PARAM
};

export const SORT_TYPES = [SORT_VIEWS_TYPE, SORT_TIME_TYPE];

export default Mixin.create({
  sort: SORT_VIEWS_TYPE,
  languageDirectoryFilter: injectService(),

  _modelForVideoType({
    videoType,
    defaultRoute,
    videoCollection,
    searchParams
  }) {
    let broadcastType = TYPE_PARAM_MAP[videoType];
    if (!broadcastType) {
      return this.transitionTo(defaultRoute, 'all');
    }

    searchParams.broadcastType = broadcastType;
    searchParams.language = this.get('languageDirectoryFilter.languageFilters').join(',');

    if (!searchParams.sort) {
      searchParams.sort = this.get('sort');
    }

    if (!searchParams.period && videoType === UPLOADED_VIDEOS_TYPE) {
      searchParams.period = UPLOAD_PERIOD_PARAM;
    }

    let videos = DeprecatedVideo.find(videoCollection, searchParams);
    if (!videos.get('isLoaded')) {
      videos.load();
    }

    return {
      videos,
      videoType,
      videoTypes: Object.keys(TYPE_PARAM_MAP),
      sort: searchParams.sort,
      sortTypes: SORT_TYPES,
      trackingContent: this.get('trackingContent')
    };
  },

  trackingContent: computed('sort', function() {
    let label = videoSortLabel(this.get('sort'));
    return `${label.toLowerCase()}_videos`;
  }),

  actions: {
    refreshModel() {
      this.refresh();
    },
    changeSort(newSort) {
      this.set('sort', newSort);
      this.refresh();
    }
  }
});
