/*
  StreamGoose Twitch backend — WebSocket PubSub API part
  
  Created by Luxferre in 2024, released into public domain
*/

package main

import (
  "fmt"

  "github.com/plugnburn/go-twitch-pubsub"
)

/* process a single PubSub message */
func tw_process_pubsub_msg(msg *twitchpubsub.PointsEvent) {
  userinput := msg.UserInput
  rewname := msg.Reward.Title
  rewcost := msg.Reward.Cost
  rewprompt := msg.Reward.Desc

  /* format the reward text */
  reward_text := fmt.Sprintf("%s redeemed %s for %d points", msg.User.DisplayName, rewname, rewcost)
  if rewprompt != "" {
    reward_text += fmt.Sprintf(" (with %s = %s)", rewprompt, userinput)
  }
  reward_text += "!"

  /* create output message */
  out_message := ChatMessage {
    Type: "tw^system^reward",
    NativeId: msg.Id,
    AuthorId: msg.User.Id,
    Timestamp: msg.RedeemedAt.UTC().Format("2006-01-02T15:04:05Z"),
    Username: msg.User.DisplayName,
    Text: reward_text,
    Icon: "",
  }

  /* finally, send it to the message broker via the message_transport channel */
  message_transport <- out_message

}

/* main loop to read PubSub messages */
func tw_ws_pubsub_readloop() {
  client := twitchpubsub.NewClient(twitchpubsub.DefaultHost)
  client.Listen("community-points-channel-v1." + TW_BROADCASTER_ID, TW_OAUTH_TOKEN)
  client.OnPointsEvent(func (channelId string, data *twitchpubsub.PointsEvent) {
    tw_process_pubsub_msg(data)
  })
  client.Start()
}
