import Ember from 'ember';
import * as commonUtils from 'corpus-common-addon/utils/utils';
import _ from 'lodash';

export default Ember.Component.extend({

    player: Ember.inject.service(),
    filter: Ember.inject.service(),
    constants: Ember.inject.service(),

    classNames: ['notice-component'],

    item: Ember.computed('model', 'player.model', function() {
        return this.get('model') || this.get('player').get('model');
    }),

    participants: Ember.computed('item.contributors', function() {
        let participants = [];
        const contributors = this.get('item.contributors') || [];
        let identifier;
        contributors.forEach(function(contributor) {
          identifier = contributor.name || contributor.url;
          var participant = participants.find(participant => participant.identifier === identifier);
          if(participant) {
              participant['role'].push(contributor.role.split('/').pop());
          } else {
              participants.push({ identifier: identifier, role: [ contributor.role.split('/').pop() ] });
          }
        });
        return participants;
    }),

    location: Ember.computed('item.geoInfo', function() {
        var location = '';
        if(this.get('item')) {
            var meta = this.get('item').get('geoInfo').notes.find(element => element.lang);
            if(meta) {
                location = meta.value;
            }
        }
        return location;
    }),

    noticeCocoonPurlUrl: Ember.computed('item', function() {
      const item = this.get('item');
      return this.get('constants').COCOON_PURL_BASE_URL + item.get('cocoonId');
    }),

    actions: {

        addThemeFilter: function(id) {
            this.get('filter').setFilter('theme', id);
        },

        addLanguageFilter: function(id) {
            this.get('filter').setFilter('language', id);
        },

        addTypeFilter: function(id) {
            this.get('filter').setFilter('discourse', id);
        },

        addCreatedFilter: function(dateStr) {
          const filter = this.get('filter');
          if(!dateStr) {
            return;
          }
          const oldDateList = filter.get('dateList');
          let newDateList = [];
          const periodMatches = commonUtils.getPeriodMatches(dateStr);
          if(periodMatches) {
            newDateList = _.range(periodMatches.start.date.getFullYear(), periodMatches.end.date.getFullYear()+1);
          } else {
            const date = new Date(dateStr);
            if (!isNaN(date.getTime())) {
              newDateList = [ date.getFullYear() ];
            }
          }
          if(newDateList.length > 0) {
            filter.set('dateList', _.union(oldDateList, newDateList));
          }
        }
    }

});
