package com.khmer9.lotto.screen.result

import android.annotation.SuppressLint
import android.media.MediaPlayer
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import com.gdtlib.lib.adapter.BaseListItem
import com.khmer9.lotto.R
import com.khmer9.lotto.app.App
import com.khmer9.lotto.app.ShareActivity
import com.khmer9.lotto.base.BaseFragment
import com.khmer9.lotto.extension.btnClick
import com.khmer9.lotto.remote.SocketMessageDataModel
import com.khmer9.lotto.util.MiddleDividerItemDecoration
import kotlinx.android.synthetic.main.fragment_result.*


/**
 * A simple [Fragment] subclass as the second destination in the navigation.
 */
class ResultFragment : BaseFragment(R.layout.fragment_result) {
    private lateinit var adapterTable1: Table1Adapter
    private lateinit var adapterTable2: Table2Adapter
    private val shareViewModel = App.injectShareViewModel()
    private lateinit var itemDecoration: MiddleDividerItemDecoration
    private lateinit var betTouch : MediaPlayer

    //private val sharePref = App.injectPrefHelper()

    var itemsTable2 : MutableList<Table2ListItem> ?= mutableListOf()
    val itemsTable1 : MutableList<Table1ListItem> ?= mutableListOf()


    //val itemsTable1 = mutableListOf<Table1ListItem>()

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

        (requireActivity() as ShareActivity).apply {
            betTouch = MediaPlayer.create(this, R.raw.bettouch)

        }
    }

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


        (requireActivity() as? ShareActivity)?.apply {

            groupToolbarIcons.isVisible = false

            view.findViewById<ImageView>(R.id.btn_close).setOnClickListener {

                if (!sharePref.getIsMute()) betTouch.start()
                it.btnClick().subscribe {
                    onBackPressed()
                }


            }
            refreshImageView.setOnClickListener {
                shareViewModel.remoteResult()

            }
            shareViewModel.getLottoMessage.observe(viewLifecycleOwner, Observer {getMessage(it)

            })
        }

        itemDecoration =
            MiddleDividerItemDecoration(requireContext(), MiddleDividerItemDecoration.ALL)
        itemDecoration.setDividerColor(
            ContextCompat.getColor(
                requireContext(),
                R.color.color_gray_800
            )
        )
        shareViewModel.remoteResult()
        shareViewModel.getResultState.observe(viewLifecycleOwner, androidx.lifecycle.Observer {
            getResult(it)
        })
        adapterTable1 = Table1Adapter()

        for (n in 1..117) {
            itemsTable1?.add(Table1ListItem(n, 0))

        }
        rv_tb1.addItemDecoration(itemDecoration)
        rv_tb1.setHasFixedSize(true)
        rv_tb1.layoutManager = GridLayoutManager(requireContext(), 13)
        rv_tb1.adapter = adapterTable1
        adapterTable1.submitList(itemsTable1 as List<BaseListItem>?)


        adapterTable2 = Table2Adapter()
        for (n in 1..117) {
            itemsTable2?.add(Table2ListItem(n, 0))
        }
        rv_tb2.addItemDecoration(itemDecoration)
        rv_tb2.setHasFixedSize(true)
        rv_tb2.layoutManager = GridLayoutManager(requireContext(), 13)
        rv_tb2.adapter = adapterTable2
        //adapterTable1.submitList(itemsTable1 as List<BaseListItem>?)

        adapterTable2.submitList(itemsTable2 as List<Table2ListItem>)


    }


    fun getResult(state: ResultViewState){
        if (state.isProgress){

            progress_tb1.isVisible= true
            progress_tb2.isVisible= true

        }else{
            progress_tb1.isVisible= false
            progress_tb2.isVisible= false

        }
        if (!state.resultList.isNullOrEmpty()){
            //1 row have 13 column
            var bigSmallIndex=0
            var nDuplicateBigSmall = 0

            var rangeIndex = 0
            var nDuplicateRange = 0

            val listBigSmall = arrayListOf<Table1ListItem>()
            for (n in 1..117) {
                listBigSmall.add(Table1ListItem(n, 0))

            }
            val listRange = arrayListOf<Table2ListItem>()
            for (n in 1..117) {
                listRange.add(Table2ListItem(n, 0))

            }
            state.resultList?.forEachIndexed { index, result ->

                if (index == 0){
                    listBigSmall[index].color=getLargeSmall(result.resultSmallOrBig)
                    listRange[index].rangeNumber= getRange(result.resultRange)

                } else{
                    if (result.resultSmallOrBig == state.resultList!![index-1].resultSmallOrBig){
                        val isBigSmall = getLargeSmall(result.resultSmallOrBig)
                        nDuplicateBigSmall+=1
                        bigSmallIndex += sameBigSmall(index, listBigSmall, bigSmallIndex,isBigSmall,nDuplicateBigSmall)


                    }else{
                        listBigSmall[index-bigSmallIndex].color=getLargeSmall(result.resultSmallOrBig)
                        nDuplicateBigSmall=0
                    }

                    if (result.resultRange == state.resultList!![index-1].resultRange){
                        val range = getRange(result.resultRange)
                        nDuplicateRange+=1
                        rangeIndex += sameRange(index, listRange, rangeIndex,range,nDuplicateRange)



                    }else{
                        listRange[index-rangeIndex].rangeNumber=getRange(result.resultRange)
                        nDuplicateRange=0
                    }



                }

            }


            adapterTable1.submitList(listBigSmall as List<BaseListItem>?)

            adapterTable2.submitList(listRange as List<BaseListItem>?)




        }

    }
    fun sameBigSmall(columnIndex: Int, arrayList: ArrayList<Table1ListItem>, bigSmallIndex: Int, isBigSmall: Int, nDuplicateBigSmall: Int): Int{
        var betweenIndex=0

            if (arrayList[columnIndex+12].color == 0){//free space

                if (nDuplicateBigSmall>1){

                    for (i in 2..nDuplicateBigSmall) arrayList[(columnIndex-bigSmallIndex)+(i*13)-1].color=isBigSmall


                }else {
                    arrayList[(columnIndex-bigSmallIndex+12)].color=isBigSmall
                }

                betweenIndex++
                return betweenIndex
            }

        return 0

    }
    fun sameRange(columnIndex: Int, arrayList: ArrayList<Table2ListItem>, rangeIndex: Int, range: Int, nDuplicateRange: Int): Int{
        var betweenIndex=0

        if (arrayList[columnIndex+12].rangeNumber == 0){//free space

            if (nDuplicateRange>1){

                for (i in 2..nDuplicateRange) arrayList[(columnIndex-rangeIndex)+(i*13)-1].rangeNumber=range


            }else {
                arrayList[(columnIndex-rangeIndex+12)].rangeNumber=range
            }

            betweenIndex++
            return betweenIndex
        }

        return 0

    }
    fun getLargeSmall(type: String): Int{
        when (type) {
            "Small" -> {
                return 1//blue
            }
            "Large" -> {
                return 2//red
            }
        }
        return 0
    }

    fun getRange(type: String): Int{
        when (type) {
            "1" -> {
                return 1
            }
            "2" -> {
                return 2
            }
            "3" -> {
                return 3
            }
            "4" -> {
                return 4
            }
            "5" -> {
                return 5
            }
        }

        return 0
    }
    @SuppressLint("SetTextI18n")
    fun getMessage(loto: SocketMessageDataModel){

        if (loto.isCountDowning() && loto.countDown ==128){
            (requireActivity() as? ShareActivity)?.apply {
                shareViewModel.remoteResult()

            }
        }

    }
}
