package com.foxx.androidcast.network.quic;

/*********************************************************************
 * CronetEngineProvider.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 CronetEngineProvider
 * Contributors:
 *    - Anton Afanasyeu <a.afanasieff@gmail.com> (2 commits, 57 lines)
 *    - Cursor Agent (project assistant)
 * Digest: SHA256	39f9f6c05214d52370267e6cabb02a4b4f64e43894dffaa507ab818017e3e8b6
**********************************************************************/
import android.content.Context;

import com.google.android.gms.net.CronetProviderInstaller;
import com.google.android.gms.tasks.Tasks;

import org.chromium.net.CronetEngine;
import org.chromium.net.ExperimentalCronetEngine;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/** Shared Cronet engine with QUIC / HTTP3 enabled for experimental cast transport. */
public final class CronetEngineProvider {
    private static final AtomicReference<CronetEngine> ENGINE = new AtomicReference<>();

    private CronetEngineProvider() {}

    public static CronetEngine getEngine(Context context) throws Exception {
        CronetEngine existing = ENGINE.get();
        if (existing != null) {
            return existing;
        }
        synchronized (CronetEngineProvider.class) {
            existing = ENGINE.get();
            if (existing != null) {
                return existing;
            }
            Context app = context.getApplicationContext();
            Tasks.await(CronetProviderInstaller.installProvider(app), 30, TimeUnit.SECONDS);
            ExperimentalCronetEngine.Builder builder =
                    new ExperimentalCronetEngine.Builder(app)
                            .enableQuic(true)
                            .enableHttp2(true)
                            .setStoragePath(app.getCacheDir().getAbsolutePath())
                            .enableHttpCache(CronetEngine.Builder.HTTP_CACHE_DISK, 256 * 1024);
            CronetEngine built = builder.build();
            ENGINE.set(built);
            return built;
        }
    }

    public static void shutdown() {
        CronetEngine e = ENGINE.getAndSet(null);
        if (e != null) {
            e.shutdown();
        }
    }
}
