package com.sd.cavphmi.ui.fragment

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.fragment.app.Fragment
import com.unity3d.player.IUnityPlayerLifecycleEvents
import com.unity3d.player.UnityPlayer


/**
 * A simple [Fragment] subclass.
 * Use the [UnityFragment.newInstance] factory method to
 * create an instance of this fragment.
 */
class UnityFragment : Fragment(), IUnityPlayerLifecycleEvents {

    // region Lifecycle Management - MUST BE FORWARDED TO UnityPlayer
    override fun onResume() {
        super.onResume()
        mUnityPlayer.onResume()
    }

    override fun onStart() {
        super.onStart()
        mUnityPlayer.onStart()
    }

    override fun onPause() {
        super.onPause()
        mUnityPlayer.onPause()
    }

    override fun onStop() {
        super.onStop()
        mUnityPlayer.onStop()
    }

    override fun onDestroy() {
        super.onDestroy()
        try {
            this.mUnityPlayer.destroy()
        }catch (e: Exception){

        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // 创建一个简单的 FrameLayout 作为 Fragment 的根视图
        val frameLayout = FrameLayout(requireContext())
        frameLayout.layoutParams = ViewGroup.LayoutParams(-1, -1)
//        // 将 UnityPlayer 的视图添加到 FrameLayout 中
        mUnityPlayer.let { unityPlayer ->
//            val playerView = unityPlayer
            val layoutParams = ViewGroup.LayoutParams(-1, -1)
            frameLayout.addView(unityPlayer, layoutParams)
        }
        return frameLayout
//        return inflater.inflate(R.layout.fragment_unity, container, false)
    }



    override fun onUnityPlayerUnloaded() {
        Log.d("UnityFragment", "-----------------onUnityPlayerUnloaded")
        // Unity 玩家未加载时调用
        activity?.finish()
    }

    override fun onUnityPlayerQuitted() {
        Log.d("UnityFragment", "-----------------onUnityPlayerQuitted")
    }


    // UnityPlayer 实例
    private lateinit var mUnityPlayer: UnityPlayer


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mUnityPlayer = UnityPlayer(requireContext(),this)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        // 视图创建完成后，可以在这里进行最终设置
        mUnityPlayer.windowFocusChanged(true)
//        mUnityPlayer.requestFocus()
    }

    // 可选：向 Unity 发送消息的方法
    fun sendMessageToUnity(gameObjectName: String, methodName: String, message: String) {
//        mUnityPlayer?.sendMessage(gameObjectName, methodName, message)
//        UnityPlayer.UnitySendMessage()
    }




    companion object {
        @JvmStatic
        fun newInstance() = UnityFragment()

    }
}