<template>
  <div class="grid grid-cols-[1fr_1fr] gap-2">
    <GalleryCard
      v-for="producer in producers"
      :key="`producer-${producer.id}`"
      :client="me!"
      :producer="producer"
    />

    <GalleryCard
      v-for="consumer in consumers"
      :key="`consumer-${consumer.consumer.id}`"
      :client="consumer.client"
      :consumer="consumer.consumer"
    />
  </div>
</template>

<script setup lang="ts">
import type { ChadClient, Consumer, Producer } from '#shared/types'

definePageMeta({
  name: 'Gallery',
})

const { videoProducer, shareProducer } = useMediasoup()
const { clients, me } = useClients()

const producers = computed(() => {
  return [videoProducer.value, shareProducer.value].filter(p => !!p && !!p.raw.track) as Producer[]
})

const consumers = computed(() => {
  return clients.value.reduce<{ client: ChadClient, consumer: Consumer }[]>((acc, client) => {
    const { streaming, videoConsumers: clientVideoConsumers, shareConsumers: clientShareConsumers } = useClient(client.socketId)

    if (!streaming.value)
      return acc

    for (const consumer of [...clientVideoConsumers.value, ...clientShareConsumers.value]) {
      acc.push({ client, consumer })
    }

    return acc
  }, [])
})

const hasItems = computed(() => producers.value.length > 0 || consumers.value.length > 0)

watch(hasItems, (hasItems) => {
  if (hasItems)
    return

  navigateTo({ name: 'Index' })
})
</script>
