package com.example.psp.viewmodel

import android.app.Application
import android.webkit.WebSettings
import android.webkit.WebView
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class WebViewViewModel @Inject constructor(
    application: Application
) : AndroidViewModel(application) {

    private var _preloadedWebView: WebView? = null
    val preloadedWebView: WebView?
        get() = _preloadedWebView

    init {
        preloadWebView()
    }

    private fun preloadWebView() {
        viewModelScope.launch {
            _preloadedWebView = WebView(getApplication()).apply {
                overScrollMode = android.view.View.OVER_SCROLL_NEVER
                webChromeClient = android.webkit.WebChromeClient()
                // Apply the same settings as in WebViewScreen
                settings.apply {
                    javaScriptEnabled = true
                    domStorageEnabled = true
                    cacheMode = WebSettings.LOAD_DEFAULT
                    loadsImagesAutomatically = true
                    allowFileAccess = true
                    useWideViewPort = true
                    loadWithOverviewMode = true
                    mixedContentMode = WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE
                    setSupportZoom(false)
                    builtInZoomControls = false
                    displayZoomControls = false
                }
                // Load the URL to preload
                loadUrl("https://tis.shift-am.ir")
            }
        }
    }

    override fun onCleared() {
        super.onCleared()
        _preloadedWebView?.destroy()
        _preloadedWebView = null
    }
}
