import DS from 'ember-data';
import Ember from 'ember';
import _ from 'lodash';

export default DS.Model.extend({
    constants: Ember.inject.service(),

    cocoonId: DS.attr('string'),
    uri: DS.attr('string'),
    issued: DS.attr('date'),
    created: DS.attr('string'),
    title: DS.attr('string'),
    rights: DS.attr('string'),
    countryCode: DS.attr('string'),
    alternativeTitle: DS.attr('string'),
    languages: DS.attr({ defaultValue: function() { return []; } }),
    publisher: DS.attr('string'),
    transcript_url: DS.attr('string'),
    transcript: DS.attr({ defaultValue: function() { return {}; } }),

    publishers: DS.attr({ defaultValue: function() { return []; } }),
    contributors: DS.attr({ defaultValue: function() { return []; } }),
    geoInfo: DS.attr({ defaultValue: function() { return {}; } }),
    mediaArray: DS.attr({ defaultValue: function() { return []; } }),
    subjects: DS.attr({ defaultValue: function() { return []; } }),
    types: DS.attr({ defaultValue: function() { return []; } }),
    descriptions: DS.attr({ defaultValue: function() { return []; } }),

    duration_ms: DS.attr('number', {
        defaultValue: () => {
            var self = this;
            var duration = 0;
            Object.keys(this.get('mediaArray')).forEach(function(key) {
                if (!duration && self.get('mediaArray')[key].extent_ms) {
                    duration = self.get('mediaArray')[key].extent_ms;
                }
            });
            return duration;
        }
    }),

    media: Ember.computed('mediaArray', function() {
        var arrayMedia = [];
        var master = null;
        _.forEach(this.get('mediaArray'), function(media) {
            var index = arrayMedia.findIndex(element => element.format === media.format);
            if(media.master) {
              master = media;
            }
            if(index === -1 && !media.master) {
                arrayMedia.push(media);
            }
        });
        arrayMedia.sort((m1, m2) => {

          const f1 = m1.format;
          const f2 = m2.format;
          const w1 = this.get('constants').MEDIA_TYPE_WEIGHT[f1] || 0;
          const w2 = this.get('constants').MEDIA_TYPE_WEIGHT[f2] || 0;

          return w1-w2;
        });
        if(arrayMedia.length === 0 && master) {
          arrayMedia.push(master);
        }
        return arrayMedia;
    }),

    video: Ember.computed('media', function() {
        return this.get('media').findIndex(element => element.format.match(new RegExp('^video/'))) > -1;
    }),

    duration: Ember.computed( 'duration_ms', function() {
        return this.get('duration_ms')/1000;
    }),

    publishers_disp: Ember.computed('publisher', 'publishers', function() {
        return this.get('publisher')?this.get('publisher'):this.get('publishers').join(', ');
    })

});
