package com.peterino.blastoise

import android.os.Handler
import android.os.Looper

enum class PlaybackSourceMode {
    RADIO,
    LIBRARY,
}

enum class AuthState {
    CHECKING,
    SIGNED_OUT,
    GUEST,
    SIGNED_IN,
}

data class PlaybackSnapshot(
    val sourceMode: PlaybackSourceMode = PlaybackSourceMode.RADIO,
    val authState: AuthState = AuthState.CHECKING,
    val currentUser: UserSession? = null,
    val status: String = "Starting",
    val channels: List<ChannelInfo> = emptyList(),
    val libraryTracks: List<Track> = emptyList(),
    val libraryLoaded: Boolean = false,
    val myPlaylists: List<Playlist> = emptyList(),
    val sharedPlaylists: List<Playlist> = emptyList(),
    val playlistsLoaded: Boolean = false,
    val selectedPlaylistId: String? = null,
    val selectedPlaylist: Playlist? = null,
    val currentChannelId: String? = null,
    val currentTrackId: String? = null,
    val localLibraryIndex: Int = -1,
    val currentRoomListeners: List<String> = emptyList(),
    val paused: Boolean = true,
    val queue: List<Track> = emptyList(),
    val queueLoaded: Boolean = false,
    val currentIndex: Int = 0,
    val playbackMode: String = "repeat-all",
    val channelName: String = "No channel",
    val trackTitle: String = "No track",
    val trackDuration: Double = 0.0,
    val serverTimestampMs: Long = 0L,
    val stateRealtimeMs: Long = 0L,
    val expectedPositionMs: Long = 0L,
    val playerPositionMs: Long = 0L,
    val driftMs: Long = 0L,
    val playbackState: String = "none",
    val isPlaying: Boolean = false,
    val debugEvents: List<String> = emptyList(),
)

interface PlaybackSnapshotListener {
    fun onPlaybackSnapshot(snapshot: PlaybackSnapshot)
}

object PlaybackBridge {
    private val mainHandler = Handler(Looper.getMainLooper())
    private val listeners = linkedSetOf<PlaybackSnapshotListener>()

    @Volatile
    var service: PlaybackService? = null

    @Volatile
    var snapshot: PlaybackSnapshot = PlaybackSnapshot()
        private set

    fun register(listener: PlaybackSnapshotListener) {
        mainHandler.post {
            listeners.add(listener)
            listener.onPlaybackSnapshot(snapshot)
        }
    }

    fun unregister(listener: PlaybackSnapshotListener) {
        mainHandler.post {
            listeners.remove(listener)
        }
    }

    fun publish(next: PlaybackSnapshot) {
        mainHandler.post {
            snapshot = next
            listeners.toList().forEach { it.onPlaybackSnapshot(next) }
        }
    }
}
