/*
  StreamGoose YouTube backend — Go reference implementation
  
  Created by Luxferre in 2024, released into public domain
*/

package main

import (
  "log"
  "slices"
  "time"
)

const YT_ID_CACHE_LIMIT = 1000

/* global message ID cache */
var yt_msg_id_cache []string
/* debug flag */
var YT_DEBUG bool

/* entry point */
func youtube_run(config map[string]interface{}) {
  API_POLL_TIMEOUT := 2 /* polling timeout in seconds */

  if _, ok := config["yt_api_poll_timeout"]; ok {
    API_POLL_TIMEOUT = int(config["yt_api_poll_timeout"].(float64))
  }

  YT_INNER_USERAGENT = config["useragent"].(string)
  YT_DEBUG = false
  if _, ok := config["debug"]; ok {
    YT_DEBUG = config["debug"].(bool)
  }

  video_id := "" /* video broadcast ID is empty by default */
  if _, ok := config["yt_video_id"]; ok { /* override the video broadcast ID */
    video_id = config["yt_video_id"].(string)
  } else { /* no video ID supplied, begin with the usual flow */
    video_id = config["yt_channel"].(string)
  }

  opts := yt_inner_get_chat_options(video_id) 
  
  log.Println("StreamGoose YouTube Go backend started")

  yt_msg_id_cache = append(yt_msg_id_cache, "") /* init the cache */
  for { /* main loop */
    chatitems := yt_inner_get_chat_data(&opts) 
    for _, msg := range chatitems {
      if !slices.Contains(yt_msg_id_cache, msg.Timestamp + msg.Username) { /* we have a fresh message here */
        /* send it to the message broker via the message_transport channel */
        message_transport <- msg

        /* update the ID cache */
        yt_msg_id_cache = append(yt_msg_id_cache, msg.Timestamp + msg.Username)
        cachelen := len(yt_msg_id_cache)
        if cachelen > YT_ID_CACHE_LIMIT { /* trim the excess */
          yt_msg_id_cache = yt_msg_id_cache[cachelen-YT_ID_CACHE_LIMIT:cachelen]
        }
      }
    }
    time.Sleep(time.Duration(API_POLL_TIMEOUT) * time.Second)
  }
}
