components_GetShuffleItemsTask.bs

import "pkg:/source/api/ApiClient.bs"
import "pkg:/source/utils/misc.bs"

sub init()
  m.top.functionName = "getShuffleItems"
end sub

' Fetches items to shuffle for Series, Season, and Person item types off the render thread.
' Writes the combined result array to m.top.shuffleItems (empty array = nothing to play).
sub getShuffleItems()
  input = m.top.shuffleInput
  items = []

  if input.type = "Series"
    data = GetApi().GetEpisodes(input.id, { SortBy: "Random", Limit: 200 })
    if isValid(data) and isValid(data.Items) then items = data.Items
  else if input.type = "Season"
    ' Shuffle episodes within this season only
    data = GetApi().GetEpisodes(input.seriesId, { SeasonId: input.id, SortBy: "Random", Limit: 200 })
    if isValid(data) and isValid(data.Items) then items = data.Items
  else if input.type = "Person"
    ' All movies featuring this person (watched or not — rewatching a film is fine)
    moviesData = GetApi().GetItemsByQuery({
      personIds: input.id,
      recursive: true,
      includeItemTypes: "Movie",
      Limit: 250
    })
    ' Watched episodes/recordings only — avoids spoiling shows the user is mid-way through
    episodesData = GetApi().GetItemsByQuery({
      personIds: input.id,
      recursive: true,
      includeItemTypes: "Episode,Recording",
      isPlayed: true,
      Limit: 250
    })
    if isValid(moviesData) and isValid(moviesData.Items) then items.append(moviesData.Items)
    if isValid(episodesData) and isValid(episodesData.Items) then items.append(episodesData.Items)
  else if input.type = "BoxSet"
    data = GetApi().GetItemsByQuery({
      "ParentId": input.id,
      "SortBy": "Random",
      "Limit": 200,
      "EnableTotalRecordCount": false
    })
    if isValid(data) and isValid(data.Items) then items = data.Items
  end if

  m.top.shuffleItems = items
end sub