package com.ccwangluo.accelerator.ui.web

import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.fragment.app.Fragment
import com.ccwangluo.accelerator.databinding.FragmentWebviewBinding
import com.just.agentweb.core.AgentWeb
import com.just.agentweb.core.client.DefaultWebClient
import com.xuexiang.xpage.annotation.Page
import com.xuexiang.xpage.base.XPageFragment


@Page(name = "webview")
class CommonWebViewFragment : XPageFragment() {

    var agentWeb: AgentWeb? = null
    lateinit var binding: FragmentWebviewBinding
    override fun inflateView(inflater: LayoutInflater?, container: ViewGroup?): View {
        binding = FragmentWebviewBinding.inflate(inflater!!, container, false)
        return binding.root
    }

    override fun initViews() {
        val url = arguments?.getString(WEBVIEW_URL_KEY)
        agentWeb =
            url?.let { createAgentWeb(this, binding.commonWebview, it) }
        agentWeb?.getJsInterfaceHolder()
            ?.addJavaObject("android", AndroidInterface(this, agentWeb!!))
    }

    fun createAgentWeb(fragment: Fragment?, viewGroup: ViewGroup, url: String): AgentWeb {
        return AgentWeb.with(fragment!!)
            .setAgentWebParent(
                viewGroup!!,
                -1,
                FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT
                )
            )
            .useDefaultIndicator(-1, 3)
            .setOpenOtherPageWays(DefaultWebClient.OpenOtherPageWays.ASK)
            .createAgentWeb()
            .ready()
            .go(url)
    }

    override fun initListeners() {

    }

    override fun onPause() {
        agentWeb?.getWebLifeCycle()?.onPause()
        super.onPause()
    }

    override fun onResume() {
        agentWeb?.getWebLifeCycle()?.onResume()
        super.onResume()
    }

    override fun onDestroyView() {
        agentWeb?.getWebLifeCycle()?.onDestroy()
        super.onDestroyView()
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            agentWeb?.let {
                if (it.back()) {
                    return true
                }
            }
        }
        return super.onKeyDown(keyCode, event)
    }


    companion object {
        var WEBVIEW_URL_KEY = "WEBVIEW_URL_KEY"
    }
}