export function parsePubSubPayload(pubSubData) {
  if (!pubSubData) { return; }

  let pubSubPayload = JSON.parse(pubSubData);
  if (pubSubPayload.type === 'bits-pin-event' && pubSubPayload.msg) {
    return JSON.parse(pubSubPayload.msg);
  }
}

export function unmarshallPinnedCheerPayload(payload) {
  let recentCheer = null;
  let topCheer = null;

  if (payload.recent.has_recent_event) {
    let timestamp = new Date(Number(payload.recent.timestamp)/1000000);

    recentCheer = _parseCommonPinnedData(payload.recent);
    recentCheer.date = new Date(timestamp);
    recentCheer.payday_timestamp = Number(payload.recent.timestamp);
    recentCheer.duration = payload.recent.time_remaining_ms / 1000;
    recentCheer.totalDuration = payload.recent.allotted_time_ms / 1000;
  }

  if (payload.top.has_top_event) {
    topCheer = _parseCommonPinnedData(payload.top);
  }

  let unmarshalledPayload = {
    top: topCheer,
    recent: recentCheer
  };

  return unmarshalledPayload;

  function _parseCommonPinnedData(pinPayload) {
    let payloadTags = pinPayload.tags;

    let tags = {
      id: Number(pinPayload.user_id),
      roomid: Number(pinPayload.channel_id),
      bits: pinPayload.bits_used,
      emotes: _getEmotes(payloadTags.emotes),
      msgid: payloadTags.msg_id,
      badges: _getBadges(payloadTags.badges),
      'display-name': payloadTags.display_name
    };

    let commonPayload = {
      amount: pinPayload.bits_used,
      color: pinPayload.tags.color,
      from: pinPayload.username,
      id: pinPayload.user_id,
      message: pinPayload.message,
      tags: tags,
      channel_id: pinPayload.channel_id,
      message_id: pinPayload.message_id
    };

    return commonPayload;
  }

  function _getBadges(badges) {
    let badgesObj = {};
    badges.forEach((badge) => {
      if (!badge.badge_set_id) { return; }
      badgesObj[badge.badge_set_id] = badge.badge_set_version;
    });
    return badgesObj;
  }

  function _getEmotes(emotes) {
    let emotesObj = {};
    emotes.forEach((emote) => {
      if (!emote.id) { return; }
      emotesObj[emote.id] = emotesObj[emote.id] || [];
      let emotePosition = [emote.start, emote.end];
      emotesObj[emote.id].push(emotePosition);
    });
    return emotesObj;
  }
}
