package ru.forbion.f7cloud.mobile

import android.content.Context
import android.view.ViewGroup
import android.webkit.WebView
import ru.forbion.f7cloud.feature.files.OfficeEditorLaunch

/**
 * Держит один настроенный WebView между открытиями редактора (тот же пользователь/сервер).
 * Статика Collabora подтягивается из HTTP-кэша WebView при повторных loadUrl.
 */
internal object OfficeWebViewPool {
    private var webView: WebView? = null
    private var sessionKey: String? = null
    private var recycledAtMs: Long = 0L

    private const val MAX_IDLE_MS = 15 * 60 * 1000L

    fun sessionKey(launch: OfficeEditorLaunch): String =
        "${launch.serverUrl.trimEnd('/')}|${launch.username}"

    fun obtain(
        context: Context,
        launch: OfficeEditorLaunch,
        configure: (WebView) -> Unit,
    ): WebView {
        evictIfStale()
        val key = sessionKey(launch)
        val existing = webView
        if (existing != null && sessionKey == key) {
            detach(existing)
            configure(existing)
            return existing
        }
        dispose()
        val created = WebView(context).apply { configure(this) }
        webView = created
        sessionKey = key
        recycledAtMs = 0L
        return created
    }

    fun recycle(view: WebView?) {
        if (view == null || view !== webView) return
        detach(view)
        view.stopLoading()
        recycledAtMs = System.currentTimeMillis()
    }

    fun dispose() {
        webView?.destroy()
        webView = null
        sessionKey = null
        recycledAtMs = 0L
    }

    fun evictIfStale() {
        if (webView == null) return
        if (recycledAtMs > 0L && System.currentTimeMillis() - recycledAtMs > MAX_IDLE_MS) {
            dispose()
        }
    }

    private fun detach(view: WebView) {
        (view.parent as? ViewGroup)?.removeView(view)
    }
}
