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 androidx.fragment.app.activityViewModels
import com.sd.cavphmi.viewmodels.UnityMapVm
import com.unity3d.player.IUnityPlayerLifecycleEvents
import com.unity3d.player.UnityPlayer
import kotlin.getValue


/**
 * 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
    //UNITY map 控制类
    private val unityMapVm: UnityMapVm by activityViewModels()


    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()
        //使用拼接服务器资源加载地图
        unityMapVm.loadTileJson()
    }


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

}