package com.ponzischeme89.memby

import android.app.Application
import coil.Coil
import coil.ImageLoader
import coil.disk.DiskCache
import coil.memory.MemoryCache
import com.ponzischeme89.memby.data.remote.HttpStack
import okhttp3.OkHttpClient
import java.util.concurrent.TimeUnit

class MembyApp : Application() {
    override fun onCreate() {
        super.onCreate()
        Coil.setImageLoader(
            ImageLoader.Builder(this)
                // Coil builds its own OkHttpClient when not given one, which would mean a
                // third connection pool alongside the Emby and gateway APIs. In gateway
                // mode artwork is proxied by the same HTTPS host that serves /v1/home, so
                // sharing the stack lets every poster resume the connection the home
                // request already opened rather than repeating the TLS handshake.
                .okHttpClient { artworkHttpClient() }
                .memoryCache {
                    MemoryCache.Builder(this)
                        // A backdrop is requested at 1280x720 — 3.7MB as ARGB_8888 — and
                        // it is replaced on every focus change. At the previous 8% the
                        // cache held barely two of them before a poster could be cached
                        // at all, so ordinary D-pad movement re-decoded artwork it had
                        // just evicted. These are hardware bitmaps (allowHardware is on
                        // at every call site), so the extra headroom is graphics memory
                        // rather than Java heap.
                        .maxSizePercent(0.25)
                        .build()
                }
                .diskCache {
                    DiskCache.Builder()
                        .directory(cacheDir.resolve("media_artwork"))
                        .maxSizeBytes(128L * 1024L * 1024L)
                        .build()
                }
                // Emby artwork URLs include an image tag, so changed artwork gets a new
                // cache key. Keep tagged thumbnails available even when a server sends
                // conservative cache headers.
                .respectCacheHeaders(false)
                .crossfade(false)
                .build(),
        )
        ServiceLocator.init(this)
    }

    /**
     * Artwork tolerates a shorter read timeout than the API does: a poster that has not
     * arrived in ten seconds has already missed the moment it was wanted for, and the
     * card falls back to its placeholder.
     */
    private fun artworkHttpClient(): OkHttpClient = HttpStack.base.newBuilder()
        .connectTimeout(10, TimeUnit.SECONDS)
        .readTimeout(10, TimeUnit.SECONDS)
        .build()
}
