package com.ponzischeme89.memby.ui.player

import androidx.tracing.Trace
import java.util.concurrent.atomic.AtomicInteger

/**
 * Names the two spans of a playback launch in a systrace, so `:benchmark` can measure
 * what [PlaybackTrace] can only log.
 *
 * The log line is for reading after the fact; these are for a machine that has to compare
 * a hundred launches and tell you whether a change made things worse. They measure the same
 * two things, from the same three points in [PlayerActivity], which is why the names live
 * here beside each other rather than being typed into a benchmark and a player separately —
 * `:benchmark` imports [LAUNCH] and [FIRST_FRAME] by reference, so a rename cannot quietly
 * turn the benchmark into one that measures nothing and reports zero.
 *
 * These are *async* sections deliberately: a launch begins on the main thread in `onCreate`
 * and ends in a media3 callback, and a synchronous begin/end pair cannot span that.
 *
 * Everything here is a no-op unless a trace is being captured, so this costs a released
 * build an atomic increment and a boolean check per playback.
 */
internal object PlaybackTraceSections {

    /** The viewer pressed Play until there is a picture. What they actually experience. */
    const val LAUNCH = "Memby.playbackLaunch"

    /**
     * `prepare()` until there is a picture: opening the file over HTTP, seeking to the
     * resume point, and initialising a decoder. Measured separately because it is by far
     * the largest share of a resume, and the one that a change to the player's HTTP stack
     * or buffering would move.
     */
    const val FIRST_FRAME = "Memby.playbackFirstFrame"

    private val cookies = AtomicInteger()

    /** A cookie distinguishing overlapping sections; auto-advance can start one while the
     * previous episode's is still open. */
    fun nextCookie(): Int = cookies.incrementAndGet()

    fun begin(name: String, cookie: Int) {
        if (Trace.isEnabled()) Trace.beginAsyncSection(name, cookie)
    }

    fun end(name: String, cookie: Int) {
        if (Trace.isEnabled()) Trace.endAsyncSection(name, cookie)
    }
}
