package moe.lava.neon.core.data.guild

import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.filterIsInstance
import kotlinx.coroutines.flow.flatMapConcat
import kotlinx.coroutines.flow.map
import moe.lava.neon.api.gateway.Event
import moe.lava.neon.api.gateway.GatewayHandler
import moe.lava.neon.core.model.Guild
import moe.lava.neon.api.objects.Guild as ApiGuild

class GuildGatewayDataSource(
    gateway: GatewayHandler,
) {
    @OptIn(ExperimentalCoroutinesApi::class)
    val flow = gateway.events
        .filterIsInstance<Event.Ready>()
        .flatMapConcat { it.guilds.asFlow() }
        .filterIsInstance<ApiGuild.Gateway>()
        .map { apiGuild ->
            Guild(
                id = apiGuild.id,
                name = apiGuild.properties.name,
                iconHash = apiGuild.properties.icon,
            )
        }
}
