import Ember from 'ember';

const { copy, set } = Ember;

export function normalizeReactions (reactions) {
  let reactionsArray = [];
  let reactionKeys = Object.keys(reactions);
  for (let i = 0, len = reactionKeys.length; i < len; i++) {
    let key = reactionKeys[i];
    let reactionObj = {
      emoteId: parseInt(key) || 'endorse',
      emoteName: reactions[key].emote,
      count: reactions[key].count,
      userIds: reactions[key].user_ids
    };
    reactionsArray.push(reactionObj);
  }
  return reactionsArray;
}

export function mergeReactions (reactions, reactionsToMerge) {
  reactionsToMerge = copy(reactionsToMerge);
  reactions = reactions.filter(reaction => {
    let {emoteId} = reaction;
    if (emoteId in reactionsToMerge) {
      set(reaction, 'count', reactionsToMerge[emoteId].count);
      delete reactionsToMerge[emoteId];
      return true;
    }
  });
  return [...reactions, ...normalizeReactions(reactionsToMerge)];
}
