package com.ccgui.mobile

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.webkit.ValueCallback
import android.webkit.WebChromeClient
import android.webkit.WebResourceRequest
import android.webkit.WebResourceResponse
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.Toast
import androidx.core.content.FileProvider
import androidx.webkit.WebViewAssetLoader
import java.io.File

/**
 * CCGUI 移动端：单 Activity + WebView，内置已测试通过的 H5 客户端（assets/mobile.html）。
 * 通过 WebViewAssetLoader 以 https://appassets.androidplatform.net 源加载本地页面，
 * 再开启 MIXED_CONTENT_ALWAYS_ALLOW，使其既能连中继 wss://，也能直连局域网 ws://。
 */
class MainActivity : Activity() {

    private lateinit var webView: WebView
    private var filePathCallback: ValueCallback<Array<Uri>>? = null
    private var cameraImageUri: Uri? = null
    private var lastBackTime = 0L

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        webView = WebView(this)
        setContentView(webView)

        val s = webView.settings
        s.javaScriptEnabled = true
        s.domStorageEnabled = true          // localStorage：保存的连接
        s.databaseEnabled = true
        s.mediaPlaybackRequiresUserGesture = false
        s.allowFileAccess = true
        s.allowContentAccess = true
        s.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW // 允许 https 页连 ws:// 局域网
        s.cacheMode = WebSettings.LOAD_DEFAULT
        s.textZoom = 100
        WebView.setWebContentsDebuggingEnabled(true)

        val assetLoader = WebViewAssetLoader.Builder()
            .addPathHandler("/assets/", WebViewAssetLoader.AssetsPathHandler(this))
            .build()

        webView.webViewClient = object : WebViewClient() {
            override fun shouldInterceptRequest(
                view: WebView,
                request: WebResourceRequest
            ): WebResourceResponse? = assetLoader.shouldInterceptRequest(request.url)
        }

        webView.webChromeClient = object : WebChromeClient() {
            override fun onShowFileChooser(
                view: WebView,
                callback: ValueCallback<Array<Uri>>,
                params: FileChooserParams
            ): Boolean {
                filePathCallback?.onReceiveValue(null)
                filePathCallback = callback
                openImageChooser()
                return true
            }
        }

        if (savedInstanceState != null) {
            webView.restoreState(savedInstanceState)
        } else {
            webView.loadUrl("https://appassets.androidplatform.net/assets/mobile.html")
        }
    }

    /** 弹出「相册/文件 + 拍照」二合一选择器（供 H5 的图片按钮使用） */
    private fun openImageChooser() {
        val content = Intent(Intent.ACTION_GET_CONTENT).apply {
            addCategory(Intent.CATEGORY_OPENABLE)
            type = "image/*"
        }
        var cameraIntent: Intent? = null
        cameraImageUri = null
        try {
            val dir = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
            val photo = File.createTempFile("cap_", ".jpg", dir)
            cameraImageUri = FileProvider.getUriForFile(this, "$packageName.fileprovider", photo)
            cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE).apply {
                putExtra(MediaStore.EXTRA_OUTPUT, cameraImageUri)
                addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
            }
        } catch (e: Exception) {
            cameraImageUri = null
        }

        val chooser = Intent(Intent.ACTION_CHOOSER).apply {
            putExtra(Intent.EXTRA_INTENT, content)
            putExtra(Intent.EXTRA_TITLE, "选择图片")
            if (cameraImageUri != null) {
                putExtra(Intent.EXTRA_INITIAL_INTENTS, arrayOf(cameraIntent))
            }
        }
        try {
            startActivityForResult(chooser, REQ_FILE)
        } catch (e: Exception) {
            filePathCallback?.onReceiveValue(null)
            filePathCallback = null
        }
    }

    @Deprecated("startActivityForResult 回调，简单场景仍适用")
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode != REQ_FILE) return
        val cb = filePathCallback ?: return
        filePathCallback = null
        if (resultCode != RESULT_OK) {
            cb.onReceiveValue(null)
            return
        }
        val picked: Uri? = data?.data ?: cameraImageUri // 相册结果在 data.data；拍照结果落到 cameraImageUri
        cb.onReceiveValue(if (picked != null) arrayOf(picked) else null)
    }

    @Deprecated("交给 H5 处理页内返回，无法处理再双击退出")
    override fun onBackPressed() {
        webView.evaluateJavascript("(window.mobileBack&&window.mobileBack())?'1':'0'") { r ->
            if (r != null && r.contains("1")) return@evaluateJavascript
            val now = System.currentTimeMillis()
            if (now - lastBackTime < 2000) {
                finish()
            } else {
                lastBackTime = now
                Toast.makeText(this, "再按一次退出", Toast.LENGTH_SHORT).show()
            }
        }
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        webView.saveState(outState)
    }

    companion object {
        private const val REQ_FILE = 1001
    }
}
