import ApplicationSerializer from './application';

export function deserializeChannel(payload) {
  let id = payload.name;
  if (payload.logo === null) {
    delete payload.logo; // We don't care about null values, but Ember-Data treats this as a real value so we can't set defaults
  }
  payload.last_accessed_at = new Date().getTime();
  return {
    type: 'channel',
    id,
    attributes: payload,
    relationships: {
      user: {
        data: { type: 'user', id }
      },
      stream: {
        data: { type: 'stream', id }
      },
      followers: {
        links: {
          related: `/kraken/channels/${id}/follows?offset=0&on_site=1&limit=24&direction=DESC`
        }
      },
      following: {
        links: {
          related: `/kraken/users/${id}/follows/channels?offset=0&on_site=1`
        }
      },
      'directory-following': {
        links: {
          related: `/kraken/users/${id}/follows/channels?offset=0&on_site=1&feature=following_directory`
        }
      },
      'sidebar-following': {
        links: {
          related: `/kraken/users/${id}/follows/channels?offset=0&on_site=1&feature=following_sidebar`
        }
      },
      events: {
        links: {
          related: `/v5/channels/${ payload._id }/events`
        }
      }
    }
  };
}

export default ApplicationSerializer.extend({
  normalizeFindRecordResponse(store, type, payload, id) {
    let data = deserializeChannel(payload);
    return this._super(store, type, { data }, id);
  },

  normalizeUpdateRecordResponse(store, type, payload, id) {
    let data = deserializeChannel(payload);
    return this._super(store, type, { data }, id);
  },

  normalizeResponse(store, type, payload, id, requestType) {
    if (!payload.follows) {
      return this._super(...arguments);
    }

    let meta = this.extractMeta(store, type, payload);

    // TODO follows will have to become something more general
    let data = payload.follows.map(follow => {
      return deserializeChannel(follow.channel);
    });
    let hash = { data, meta };
    return this._super(store, type, hash, id, requestType);
  }
});
