import JSONAPISerializer from 'ember-data/serializers/json-api';
import _ from 'lodash';

export default JSONAPISerializer.extend({

    normalizeResponse: function(store, primaryModelClass, payload, id) {
        var speakerResources = payload['resources'].find(resource => resource['id'] === 'speakers') || {'content': { 'data': []}};
        var speakers = _.reduce(
          speakerResources['content']['data'],
          function(res, s) { res[s.id] = s; return res;},
          {});
        var topicsResources = payload['resources'].find(resource => resource['id'] === 'topics') || {'content': { 'data': []}};
        var topics = _.reduce(
          topicsResources['content']['data'],
          function(res, r) { res[r.id] = r; return res;},
          {});

        var translationISO = false;

        var turns = _.reduce(payload['annotation-types'] || [], function(res, t) {
            res[t['id']] = {
                title: t['dc:title'],
                begin: t['corpus:begin'],
                end: t['corpus:end'],
                annotations: []
            };
            return res;
        },{});

        var sections = _.map(payload['lists'] || [], function(list){
          var topicRef = list['meta']['corpus:topic']?list['meta']['corpus:topic']['id-ref']:null;
          var topic = topicRef?topics[topicRef]:null;
          return {
            title: (topic && topic['desc'])?topic['desc'] : null,
            begin: list['meta']['corpus:begin'],
            end: list['meta']['corpus:end'],
            turns: _.reduce((list['items'] || []), function(res,item) {
              if(item['id-ref'] && turns[item['id-ref']]) {
                res.push(turns[item['id-ref']]);
              }
              return res;
            }, [])
          };
        });

        var currentSpeaker = null;
        var annotations = _.map(payload['annotations'] || [], function(annotation) {
            var annot = {
              original: annotation['content']['data']['content'],
              begin: annotation['begin'],
              end: annotation['end']
            };
            if(annotation['content']['data']['transl']) {
                annot['translation'] = annotation['content']['data']['transl']['@value'];
            }
            if(annotation['content']['data']['words']) {
                var words = _.map(annotation['content']['data']['words'], function(word) {

                    var morphenes = _.map(word['morphenes'] || [], function(morph) {
                      return {
                        original: morph['content']['@value'] || morph['content'],
                        translation: morph['transl']['@value'] || morph['transl'],
                        begin: morph['begin'],
                        end: morph['end']
                      };
                    });
                    return {
                        original: word['content']['@value'] || word['content'],
                        translation: word['transl']['@value'] || word['transl'],
                        begin: word['begin'],
                        end: word['end'],
                        morphenes: morphenes
                    };
                });
                annot['literal'] = words;
            }
            if(annotation['content']['data']['speaker']) {
                if(typeof annotation['content']['data']['speaker'] === 'object') {
                    var speaker = speakers[annotation['content']['data']['speaker']['id-ref']];
                    if(speaker) {
                        annot['speaker'] = speaker['name'];
                    }
                } else {
                    annot['speaker'] = annotation['content']['data']['speaker'];
                }
                annot['showSpeaker'] = (annot['speaker'] === currentSpeaker);
                currentSpeaker = annot['speaker'];
            }
            if(annotation['type'] && turns[annotation['type']]) {
              var type = turns[annotation['type']];
              annot['type'] = type;
              type.annotations.push(annot);
            }
            if(!translationISO && annotation['content']['data']['transl']) {
                translationISO = annotation['content']['data']['transl']['@language'];
            }

            return annot;
        });

        var response = {
            'data': {
                id: id,
                type: 'transcript',
                attributes: {
                    title: {},
                    annotations: annotations,
                    sections: sections,
                    turns: turns
                }
            }
        };

        if(Array.isArray(payload['meta']['dc:title'])) {
            var original = payload['meta']['dc:title'].find(function(title) { return title['@language'] !== translationISO; });
            if(original) {
                response.data.attributes.title.original = original['@value'];
            }
            var translation = payload['meta']['dc:title'].find(function(title) { return title['@language'] === translationISO; });
            if(translation) {
                response.data.attributes.title.translation = translation['@value'];
            }
        } else {
            response.data.attributes.title.original = payload['meta']['dc:title']['@value'];
        }


        return response;
    }

});
