package com.adealink.weparty.webview

import android.net.Uri
import android.os.Build
import android.webkit.ValueCallback
import android.webkit.WebChromeClient
import android.webkit.WebView
import androidx.activity.result.ActivityResultLauncher
import androidx.fragment.app.FragmentActivity
import com.adealink.frame.util.AppUtil
import com.adealink.weparty.imageselect.SelectImageContract
import com.adealink.weparty.imageselect.SelectImageRequest
import com.adealink.weparty.imageselect.model.MEDIA_TYPE_IMAGE
import com.adealink.weparty.imageselect.model.MEDIA_TYPE_VIDEO
import com.adealink.weparty.imageselect.model.MediaType

/**
 */
class CommonWebChromeClient(val webView: IWebView) : WebChromeClient() {

    private var launcher: ActivityResultLauncher<SelectImageRequest>? = null

    override fun onReceivedTitle(view: WebView?, title: String?) {
        super.onReceivedTitle(view, title)
        if (webView.webViewCallback?.isHostActive() == true) {
            webView.webViewCallback?.setTitle(title)
        }
    }

    override fun onProgressChanged(view: WebView?, newProgress: Int) {
        super.onProgressChanged(view, newProgress)
        if (webView.webViewCallback?.isHostActive() == true) {
            webView.webViewCallback?.onProgressChanged(newProgress)
        }
    }

    override fun onShowFileChooser(
        webView: WebView?,
        filePathCallback: ValueCallback<Array<Uri>>?,
        fileChooserParams: FileChooserParams?
    ): Boolean {
        val activity = AppUtil.currentActivity as? FragmentActivity ?: return false
        launcher = activity.activityResultRegistry.register(
            "SelectImage",
            SelectImageContract()
        ) {
            launcher?.unregister()
            if (it.path.isNullOrEmpty()) {
                filePathCallback?.onReceiveValue(null)
            } else {
                filePathCallback?.onReceiveValue(arrayOf(Uri.parse(it.uri)))
            }
        }
        val mediaTypeList = mutableListOf<String>()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            fileChooserParams?.acceptTypes?.forEach {
                mediaTypeList.add(it)
            }
        }
        val selectImage = mediaTypeList.contains(MEDIA_TYPE_IMAGE)
        val selectVideo = mediaTypeList.contains(MEDIA_TYPE_VIDEO)
        val selectMediaType = when {
            selectImage && selectVideo -> {
                MediaType.ALL
            }

            selectVideo -> {
                MediaType.VIDEO
            }

            else -> {
                MediaType.IMAGE
            }
        }
        launcher?.launch(SelectImageRequest(1, "", null, selectMediaType))
        return true
    }

}