package com.ray650128.gstreamer_demo_app.ui.mainScreen

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.gridlayout.widget.GridLayout
import com.ray650128.gstreamer_demo_app.Constants
import com.ray650128.gstreamer_demo_app.databinding.FragmentSplitViewBinding
import com.ray650128.gstreamer_demo_app.dp
import com.ray650128.gstreamer_demo_app.model.Device
import com.ray650128.gstreamer_demo_app.ui.monitoringScreen.MonitoringActivity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.math.sqrt

class SplitViewFragment : Fragment() {

    private var mPageNum: Int = 0
    private var splitMode = Constants.SPLIT_MODE_SINGLE
    private var streamType = VideoView.SUB_STREAM
    private var isClickable = true

    private lateinit var binding: FragmentSplitViewBinding

    private var data: ArrayList<Device> = ArrayList()

    private var videoViews: ArrayList<VideoView> = ArrayList()

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

        if (arguments != null) {
            mPageNum = requireArguments().getInt(ARG_PAGE_NUM)
            splitMode = requireArguments().getInt(ARG_SPLIT_MODE)
            isClickable = requireArguments().getBoolean(ARG_CLICKABLE)
            streamType = requireArguments().getInt(ARG_STREAM_TYPE)
            data = requireArguments().getParcelableArrayList(ARG_PAGE_DATA) ?: arrayListOf(Device())
        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        binding = FragmentSplitViewBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        initView()

        /*viewModel.activePage.observe(viewLifecycleOwner) {
            if (it == null) return@observe
            if (it == this.mPageNum) {
                MainScope().launch {
                    //delay(1000)
                    //playAll()
                }
            } else {
                //stopAll()
            }
        }*/
    }

    override fun onPause() {
        stopAll()
        super.onPause()
        Log.d("${TAG}_$mPageNum", "onPause()")
    }

    override fun onResume() {
        super.onResume()
        playAll()
        Log.d("${TAG}_$mPageNum", "onResume()")
    }

    override fun onDestroy() {
        //destroyAll()
        stopAll()
        Log.d("${TAG}_$mPageNum", "onDestroy()")
        super.onDestroy()
    }

    private fun initView() {
        // 生成 VideoView 分割畫面
        binding.apply {
            val maxRow = sqrt(splitMode.toFloat()).toInt()
            val maxCol = sqrt(splitMode.toFloat()).toInt()
            //Log.d(TAG, "maxRow: $maxRow, maxCol: $maxCol")

            baseView.rowCount = maxRow
            baseView.columnCount = maxCol

            for (col in 0 until maxCol) {
                for (row in 0 until maxRow) {
                    val videoView = VideoView(requireContext())
                    val layoutParam = GridLayout.LayoutParams().apply {
                        topMargin = 0.dp
                        bottomMargin = 0.dp
                        marginEnd = 0.dp
                        marginStart = 0.dp

                        // 調整間距
                        when (splitMode) {
                            Constants.SPLIT_MODE_FOUR -> {
                                when (col) {
                                    0 -> bottomMargin = 2.dp
                                    1 -> topMargin = 2.dp
                                }
                                when (row) {
                                    0 -> marginEnd = 2.dp
                                    1 -> marginStart = 2.dp
                                }
                            }
                            Constants.SPLIT_MODE_NINE -> {
                                if (col == 1) {
                                    topMargin = 4.dp
                                    bottomMargin = 4.dp
                                }
                                if (row == 1) {
                                    marginEnd = 4.dp
                                    marginStart = 4.dp
                                }
                            }
                            Constants.SPLIT_MODE_SIXTEEN -> {
                                if (col == 1) {
                                    topMargin = 4.dp
                                    bottomMargin = 2.dp
                                }
                                if (col == 2) {
                                    topMargin = 2.dp
                                    bottomMargin = 4.dp
                                }
                                if (row == 1) {
                                    marginStart = 4.dp
                                    marginEnd = 2.dp
                                }
                                if (row == 2) {
                                    marginStart = 2.dp
                                    marginEnd = 4.dp
                                }
                            }
                        }
                    }
                    baseView.addView(videoView, layoutParam)
                    videoViews.add(videoView)
                }
            }

            baseView.post {
                // 根據分割數量決定子項目的寬度
                val cellWidth: Int
                val cellHeight: Int
                when (splitMode) {
                    Constants.SPLIT_MODE_SINGLE -> {
                        cellWidth = (baseView.width / maxRow)
                        cellHeight = (baseView.height / maxCol)
                    }
                    else -> {
                        cellWidth = (baseView.width / maxRow) - maxRow.dp
                        cellHeight = (baseView.height / maxCol) - maxCol.dp
                    }
                }
                videoViews.forEach { videoView ->
                    videoView.layoutParams?.width = cellWidth
                    videoView.layoutParams?.height = cellHeight
                }
            }
        }

        if (isClickable) {
            for (position in videoViews.indices) {
                videoViews[position].setOnClickListener {
                    if (position >= data.size) return@setOnClickListener
                    if (!videoViews[position].isPlaying) {
                        return@setOnClickListener
                    }
                    stopAll()
                    val item = data[position]
                    val bundle = Bundle().apply {
                        //putInt(MonitoringActivity.BUNDLE_DEVICE_ID, item.id)
                        //putInt(MonitoringActivity.BUNDLE_CHANNEL_ID, item.channelId)
                        putParcelable(MonitoringActivity.BUNDLE_DEVICE, item)
                    }
                    val intent = Intent(requireContext(), MonitoringActivity::class.java)
                    intent.putExtras(bundle)
                    startActivity(intent)
                    //gotoActivity(MonitoringActivity::class.java, bundle)*/
                    //Log.d("${TAG}_$mPageNum", "check: $item")
                }
            }
        }

        setAllUrl()
    }

    private fun setAllUrl() {
        for (index in data.indices) {
            videoViews[index].setData(data[index])
            videoViews[index].setTextVisible(
                (splitMode != Constants.SPLIT_MODE_NINE && splitMode != Constants.SPLIT_MODE_SIXTEEN)
            )
        }
    }

    fun playAll() = MainScope().launch(Dispatchers.Main) {
        if (videoViews.isEmpty()) return@launch
        //delay(splitMode * Constants.CONF_DELAY_BASE_MILLIS)
        for (index in data.indices) {
            if (!videoViews[index].isReady) continue
            videoViews[index].resetRetryCount()
            videoViews[index].play()
            delay(300)
        }
    }.start()

    fun stopAll() {
        if (videoViews.isEmpty()) return
        for (index in data.indices) {
            videoViews[index].stopRetryCount()
            if (!videoViews[index].isPlaying || videoViews[index].isLoading) continue
            videoViews[index].pause()
        }
    }

    fun destroyAll() {
        if (videoViews.isEmpty()) return
        for (index in data.indices) {
            //videoViews[index].destroy()
            videoViews[index].destroySurface()
        }
    }

    companion object {
        private val TAG = SplitViewFragment::class.java.simpleName
        private const val ARG_PAGE_NUM = "page_number"
        private const val ARG_SPLIT_MODE = "split_mode"
        private const val ARG_CLICKABLE = "clickable"
        private const val ARG_PAGE_DATA = "page_data"
        private const val ARG_STREAM_TYPE = "stream_type"

        /**
         * 透過傳入的參數，生成新的 Fragment 實例
         *
         * @param pageNumber 該 Fragment 頁碼
         * @param splitMode 畫面分割模式(9/4/1分割)
         * @return 透過傳入的參數，生成新的 Fragment 實例
         */
        fun newInstance(
            pageNumber: Int,
            splitMode: Int,
            isClickable: Boolean = true,
            pageData: ArrayList<Device>,
            streamType: Int = VideoView.SUB_STREAM
        ): SplitViewFragment {
            val fragment = SplitViewFragment()
            val args = Bundle()
            args.putInt(ARG_PAGE_NUM, pageNumber)
            args.putInt(ARG_SPLIT_MODE, splitMode)
            args.putBoolean(ARG_CLICKABLE, isClickable)
            args.putParcelableArrayList(ARG_PAGE_DATA, pageData)
            args.putInt(ARG_STREAM_TYPE, streamType)
            fragment.arguments = args
            return fragment
        }
    }
}
