package com.foxx.androidcast.network;

/*********************************************************************
 * CastSessionGate.java
 * Created at: Sat 16 May 2026 18:50:36 +0200
 * Updated at: Wed 20 May 2026 15:17:13 +0200 by Anton Afanasyeu <a.afanasieff@gmail.com>
 * Commit: 5d8e82d2e60a21fff3138d2a394ee4e8b4c6dcb8
 * class CastSessionGate
 * Contributors:
 *    - Anton Afanasyeu <a.afanasieff@gmail.com> (2 commits, 44 lines)
 *    - Cursor Agent (project assistant)
 * Digest: SHA256	bffde4e7930b8ad589c9e66476fddf21a5235667811c9379979fba5bac48db5e
**********************************************************************/
/**
 * Binds to the first non-zero session id on a connection and drops stale packets from other casts.
 */
public final class CastSessionGate {
    private static final int UNBOUND = Integer.MIN_VALUE;

    private int boundSessionId = UNBOUND;

    public boolean accept(CastProtoHeader header) {
        if (header == null) {
            return true;
        }
        int sid = header.sessionId;
        if (sid == 0) {
            return true;
        }
        if (boundSessionId == UNBOUND) {
            boundSessionId = sid;
            return true;
        }
        return boundSessionId == sid;
    }

    public void reset() {
        boundSessionId = UNBOUND;
    }

    public boolean isBound() {
        return boundSessionId != UNBOUND;
    }

    public int getBoundSessionId() {
        return boundSessionId == UNBOUND ? 0 : boundSessionId;
    }
}
