package com.sambath.klaklouk_main.screen.main.cflive.result

import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import com.gdtlib.lib.adapter.BaseListItem
import com.google.android.material.button.MaterialButton
import com.google.gson.Gson
import com.sambath.klaklouk_main.R
import com.sambath.klaklouk_main.app.App
import com.sambath.klaklouk_main.app.ShareActivity
import com.sambath.klaklouk_main.base.BaseFragment
import com.sambath.klaklouk_main.extension.btnClick
import com.sambath.klaklouk_main.remote.K
import com.sambath.klaklouk_main.screen.result.Table1Adapter
import com.sambath.klaklouk_main.screen.result.Table1ListItem
import com.sambath.klaklouk_main.util.MiddleDividerItemDecoration
import kotlinx.android.synthetic.main.fragment_cf_result.*
import org.json.JSONObject

class CfResultFragment : BaseFragment(R.layout.fragment_cf_result) {
    private lateinit var adapterTable1: Table1Adapter
    private lateinit var itemDecoration: MiddleDividerItemDecoration
    private lateinit var itemsTable1: MutableList<Table1ListItem>
    private lateinit var btnClose: MaterialButton
    private val gson = Gson()
    private val shareViewModel = App.injectShareViewModel()
    private lateinit var cfResultViewModel: CfResultViewModel
    private var cirRed: Int = 0
    private var cirBlue: Int = 0
    private var cirYellow: Int = 0
    private var cirGreen: Int = 0
    private var startColumn: Int = 0
    private var newStartColumn: Int = 0
    private var column: Int = 20
    private var fixColumn: Int = 20
    override fun onCreate(savedInstanceState: Bundle?) {
        cfResultViewModel = CfResultViewModel(App.injectApiService(), App.injectPrefHelper())
        super.onCreate(savedInstanceState)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setDataTabOne()
        cfResultViewModel.getCfResuleData()
        cfResultViewModel.state.observe(viewLifecycleOwner, androidx.lifecycle.Observer {
            Log.d("dataxzsd", "data live" + it.toString())
            addResultList(it)
        })
        (requireActivity() as? ShareActivity)?.apply {
            groupToolbarIcons.isVisible = false
            btnClose = view.findViewById<MaterialButton>(R.id.btn_close)
            btnClose.setOnClickListener {
                it.btnClick().subscribe {
                    onBackPressed()
                }
            }
            refreshImageView.setOnClickListener {
                cfResultViewModel.getCfResuleData()
            }
        }
        shareViewModel.getDefinedResultAndChannel.observe(viewLifecycleOwner, Observer {
            if (!it.isNullOrEmpty()) {
                cfResultViewModel.getCfResuleData()
            }
        })
        shareViewModel.getChannelInfo.observe(viewLifecycleOwner, Observer {
            if (it != null) {
                column = it.column
                fixColumn = it.fixColumn
                startColumn = column.minus(fixColumn)
            }
        })
    }

    private fun updateColNumber(obj: JSONObject) {
        column = if (obj.has(K.Column)) {
            obj.getInt(K.Column)
        } else {
            column
        }
        fixColumn = if (obj.has(K.Fix_Column)) {
            obj.getInt(K.Fix_Column)
        } else {
            fixColumn
        }
        startColumn = column.minus(fixColumn)
    }

    private fun addResultList(it: CfResultViewState) {
        if (it.isSuccess) {
            startColumn = column.minus(fixColumn)
            if (startColumn > newStartColumn) {
                itemsTable1.clear()
                for (n in 0..119) {
                    itemsTable1.add(Table1ListItem(n, ""))
                }
                newStartColumn = startColumn
            }

            if (!it.resultList.isNullOrEmpty()) {
                shareViewModel.setResult(it.resultList!![0].name)

                for (i in 0 until (it.resultList!!.size)) { //i in 0 until (it.resultList!!.size)
                    val rowNum = it.resultList!![i].rid as Int
                    val colNum = it.resultList!![i].cid as Int
                    if (colNum > startColumn) {
                        val index = if (rowNum == 1) {
                            (14 * rowNum.minus(1)).plus(colNum.minus(startColumn.plus(1)))
                        } else {
                            (15 * rowNum.minus(1)).plus(colNum.minus(startColumn.plus(1)))
                        }
                        if (index in 0..120) {
                            itemsTable1[index].color = it.resultList!![i].color
                            itemsTable1[index].fightNo = it.resultList!![i].fightNo
                        }
                    }
                }

                adapterTable1.submitList(itemsTable1 as List<BaseListItem>?)
                adapterTable1.notifyDataSetChanged()

                txt_one.text = it.resultSummary?.number_1.toString()
                txt_two.text = it.resultSummary?.number_2.toString()
                txt_three.text = it.resultSummary?.number_3.toString()
                txt_four.text = it.resultSummary?.number_4.toString()
                txt_five.text = it.resultSummary?.number_5.toString()
                txt_six.text = it.resultSummary?.number_6.toString()
                txt_cancel.text = it.resultSummary?.cancel.toString()
            }
        }
    }

    private fun setDataTabOne() {
        itemDecoration =
            MiddleDividerItemDecoration(requireContext(), MiddleDividerItemDecoration.ALL)
        itemDecoration.setDividerColor(
            ContextCompat.getColor(
                requireContext(),
                R.color.color_gray_800
            )
        )
        adapterTable1 = Table1Adapter()
        itemsTable1 = mutableListOf()
        for (n in 0..119) {
            itemsTable1.add(Table1ListItem(n, ""))
        }
        rv_point.addItemDecoration(itemDecoration)
        rv_point.setHasFixedSize(true)
        val layoutManager =
            GridLayoutManager(requireContext(), 15, GridLayoutManager.VERTICAL, false)
        rv_point.layoutManager = layoutManager

        rv_point.adapter = adapterTable1
        adapterTable1.submitList(itemsTable1 as List<BaseListItem>?)
    }

    fun rearrangeTheArrayList(integerArrayList: MutableList<Table1ListItem>): MutableList<Table1ListItem>? {
        val resultArrayList: MutableList<Table1ListItem> = ArrayList()
        var halfLength = 0
        halfLength = if (integerArrayList.size % 8 === 1) {
            integerArrayList.size / 8 + 1
        } else {
            integerArrayList.size / 8
        }
        for (i in 0 until halfLength) {
            resultArrayList.add(integerArrayList[i])
            if (i + halfLength < integerArrayList.size) {
                resultArrayList.add(integerArrayList[i + halfLength])
            }
        }
        return resultArrayList
    }
}