package com.sambath.kunkhmer.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.google.gson.reflect.TypeToken
import com.sambath.kunkhmer.R
import com.sambath.kunkhmer.app.App
import com.sambath.kunkhmer.app.ShareActivity
import com.sambath.kunkhmer.base.BaseFragment
import com.sambath.kunkhmer.extension.btnClick
import com.sambath.kunkhmer.remote.K
import com.sambath.kunkhmer.remote.ResultSummary
import com.sambath.kunkhmer.remote.Results
import com.sambath.kunkhmer.screen.result.Table1Adapter
import com.sambath.kunkhmer.screen.result.Table1ListItem
import com.sambath.kunkhmer.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 {
//                if (!sharePref.getIsMute()) betTouch.start()
                it.btnClick().subscribe {
                    onBackPressed()
                }
            }
        }
        shareViewModel.getDefinedResultAndChannel.observe(viewLifecycleOwner, Observer {
            if (!it.isNullOrEmpty()) {
                if (newStartColumn > startColumn) {
                    itemsTable1?.clear()
                    for (n in 0..119) {
                        itemsTable1?.add(Table1ListItem(n, "cir-white"))
                    }
                    startColumn = newStartColumn
                }
                val obj = JSONObject(it)
                val resultArr = obj.getJSONArray("objCoResult")
                val sumObj = obj.getJSONObject("objSummaryCoResult")
                val sumType = object : TypeToken<ResultSummary>() {}.type
                val summary =
                    gson.fromJson<ResultSummary>(sumObj.toString(), sumType)
                txt_blue.text = summary.wala.toString()
                txt_cancel.text = summary.cancel.toString()
                txt_green.text = summary.tie.toString()
                txt_red.text = summary.meron.toString()
                if (resultArr.length() > 0) {
                    val resultType = object : TypeToken<List<Results>>() {}.type
                    val cfResultList =
                        gson.fromJson<List<Results>>(resultArr.toString(), resultType)
                    shareViewModel.setResult(cfResultList[0].name)
                    for (i in 0 until (cfResultList.size)) {
                        val rowNum = cfResultList[i].rid as Int
                        val colNum = cfResultList[i].cid as Int
                        val index = if (rowNum == 1) {
                            (19 * rowNum.minus(1)).plus(colNum.minus(startColumn.plus(1)))
                        } else {
                            (20 * rowNum.minus(1)).plus(colNum.minus(startColumn.plus(1)))
                        }
                        if (index in 0..120) {
                            itemsTable1[index].color = cfResultList[i].color.toString()
                            itemsTable1[index].fightNo = cfResultList[i].fightNo.toString()
                        }
                    }
                    adapterTable1.submitList(itemsTable1 as List<BaseListItem>?)
                    adapterTable1.notifyDataSetChanged()
                }
            }
        })
        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, "cir-white", ""))
                }
                newStartColumn = startColumn
            }
            if (!it.resultList.isNullOrEmpty()) {
                shareViewModel.setResult(it.resultList!![0].name)
                for (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) {
                            (19 * rowNum.minus(1)).plus(colNum.minus(startColumn.plus(1)))
                        } else {
                            (20 * 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.toString()
                        }
                    }
                }
                adapterTable1.submitList(itemsTable1 as List<BaseListItem>?)
                adapterTable1.notifyDataSetChanged()
                txt_blue.text = it.resultSummary?.wala.toString()
                txt_cancel.text = it.resultSummary?.cancel.toString()
                txt_green.text = it.resultSummary?.tie.toString()
                txt_red.text = it.resultSummary?.meron.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, "cir-white"))
        }
        rv_point.addItemDecoration(itemDecoration)
        rv_point.setHasFixedSize(true)
        rv_point.layoutManager = GridLayoutManager(requireContext(), 20)
        rv_point.adapter = adapterTable1
        adapterTable1.submitList(itemsTable1 as List<BaseListItem>?)
        txt_blue.text = cirBlue.toString()
        txt_cancel.text = cirYellow.toString()
        txt_green.text = cirGreen.toString()
        txt_red.text = cirRed.toString()
    }
}