import ApplicationSerializer from './application';
import injectService from 'ember-service/inject';

export default ApplicationSerializer.extend({
  community: injectService(),

  _deserializeCommunity(payload) {
    let communityService = this.get('community');
    let name = payload.name;
    // TODO: The following three properties should be returned from our server
    // which is planned for release in the next few weeks. This code prepares
    // the rest web-client consumers to assume it will be there
    let isCommunity = communityService.isActiveCommunity(name);
    let banner = isCommunity ? communityService.bannerURL(name) : null;
    let thumbnail = isCommunity ? communityService.thumbnailURL(name) : null;
    let isPromoted = communityService.isPromotedCommunity(name);
    return {
      type: 'community',
      id: payload.name,
      attributes: {
        name,
        game: payload.game,
        streams: payload.streams || 0,
        viewers: payload.viewers || 0,
        banner,
        thumbnail,
        is_community: isCommunity,
        is_promoted: isPromoted,
        promoted_channel: payload.promoted_channel
      }
    };
  },

  normalizeQueryResponse(store, type, payload, id) {
    let data = payload.communities.map(c => this._deserializeCommunity(c));
    let meta = this.extractMeta(store, type, payload);
    let hash = { data, meta };
    return this._super(store, type, hash, id);
  },

  normalizeQueryRecordResponse(store, type, payload, id) {
    let data = this._deserializeCommunity(payload.community);
    let meta = this.extractMeta(store, type, payload);
    let hash = { data, meta };
    return this._super(store, type, hash, id);
  },

  normalizeCreateRecordResponse(store, type, payload, id) {
    let data = this._deserializeCommunity(payload.community);
    let meta = this.extractMeta(store, type, payload);
    return this._super(store, type, { data, meta }, id);
  }
});
