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 android.widget.ImageView
import androidx.fragment.app.Fragment
import androidx.gridlayout.widget.GridLayout
import com.ray650128.gstreamer_demo_app.Constants
import com.ray650128.gstreamer_demo_app.DisplayUtils
import com.ray650128.gstreamer_demo_app.R
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()
    }

    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() {
        val displayUtil = DisplayUtils(requireContext())
        // 生成 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

            val cellWidth: Int
            val cellHeight: Int
            when (splitMode) {
                Constants.SPLIT_MODE_SINGLE -> {
                    cellWidth = (displayUtil.getScreenWidth() / maxRow)
                    cellHeight = (cellWidth * 0.5625).toInt()
                }
                else -> {
                    cellWidth = (displayUtil.getScreenWidth() / maxRow) - maxRow.dp
                    cellHeight = (cellWidth * 0.5625).toInt() - maxCol.dp
                }
            }

            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

                        width = cellWidth
                        height = cellHeight

                        // 調整間距
                        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)
                }
            }
        }

        if (isClickable) {
            videoViews.forEach { videoView ->
                videoView.setOnClickListener {
                    if (!videoView.isPlaying) {
                        return@setOnClickListener
                    }
                    stopAll()
                    val item = videoView.data
                    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].data = data[index]
            videoViews[index].setTextVisible(
                (splitMode != Constants.SPLIT_MODE_NINE && splitMode != Constants.SPLIT_MODE_SIXTEEN)
            )
        }
    }

    fun playAll() {
        videoViews.forEach { videoView ->
            if (videoView.isReady) {
                videoView.resetRetryCount()
                videoView.play()
            }
        }
    }

    fun stopAll() {
        videoViews.forEach { videoView ->
            videoView.stopRetryCount()
            if (videoView.isPlaying || !videoView.isLoading) {
                videoView.pause()
            }
        }
    }

    fun destroyAll() {
        videoViews.forEach { videoView ->
            //videoView.destroy()
            videoView.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
        }
    }
}
