package com.jiooption.trading.webview

import android.annotation.SuppressLint
import android.content.Context
import android.webkit.*
import com.jiooption.trading.App
import com.jiooption.trading.BuildConfig

/**
 * WebView configuration and management
 * Sets up cookies, cache, JavaScript, and security settings
 */
object WebViewManager {

    /**
     * Configure a WebView with all required settings
     */
    @SuppressLint("SetJavaScriptEnabled")
    fun setupWebView(webView: WebView, context: Context) {
        val settings = webView.settings

        // JavaScript (required for the trading platform)
        settings.javaScriptEnabled = true
        settings.javaScriptCanOpenWindowsAutomatically = false

        // DOM Storage and cache
        settings.domStorageEnabled = true
        settings.databaseEnabled = true
        settings.cacheMode = WebSettings.LOAD_DEFAULT

        // Display settings
        settings.useWideViewPort = true
        settings.loadWithOverviewMode = true
        settings.setSupportZoom(false)
        settings.builtInZoomControls = false
        settings.displayZoomControls = false

        // Mixed content (allow in debug for local dev)
        settings.mixedContentMode = if (BuildConfig.DEBUG) {
            WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
        } else {
            WebSettings.MIXED_CONTENT_NEVER_ALLOW
        }

        // Media
        settings.mediaPlaybackRequiresUserGesture = false

        // File access (disable for security)
        settings.allowFileAccess = false
        settings.allowContentAccess = false

        // Sync cookies
        syncCookies(context)

        // Enable third-party cookies for this WebView (needed for session cookies)
        CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true)

        // Set WebView background
        webView.setBackgroundColor(context.getColor(com.jiooption.trading.R.color.bg_primary))

        // Scroll behavior
        webView.isVerticalScrollBarEnabled = false
        webView.isHorizontalScrollBarEnabled = false
        webView.overScrollMode = WebView.OVER_SCROLL_NEVER
    }

    /**
     * Sync session cookies from SecureStorage to WebView CookieManager
     */
    fun syncCookies(context: Context) {
        val cookieManager = CookieManager.getInstance()
        cookieManager.setAcceptCookie(true)

        // Get session cookie from secure storage
        val sessionCookie = App.getSecureStorage().getSessionCookie()
        if (sessionCookie.isNotEmpty()) {
            val baseUrl = com.jiooption.trading.utils.Constants.BASE_URL

            // Parse and set individual cookies
            sessionCookie.split(";").forEach { cookie ->
                val trimmed = cookie.trim()
                if (trimmed.isNotEmpty()) {
                    cookieManager.setCookie(baseUrl, trimmed)
                }
            }
            cookieManager.flush()
        }
    }

    /**
     * Save cookies from WebView back to SecureStorage
     */
    fun saveCookiesFromWebView(url: String) {
        val cookieManager = CookieManager.getInstance()
        val cookies = cookieManager.getCookie(url)
        if (!cookies.isNullOrEmpty() && cookies.contains("PHPSESSID")) {
            App.getSecureStorage().saveSessionCookie(cookies)
        }
    }

    /**
     * Clear all WebView data
     */
    fun clearWebViewData(webView: WebView) {
        webView.clearCache(true)
        webView.clearHistory()
        webView.clearFormData()
        CookieManager.getInstance().removeAllCookies(null)
        CookieManager.getInstance().flush()
    }
}
