package com.khmer9.lotto.screen.main

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.AnimationDrawable
import android.graphics.drawable.Drawable
import android.media.MediaPlayer
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.animation.AlphaAnimation
import android.view.animation.Animation
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.constraintlayout.widget.Group
import androidx.core.animation.doOnEnd
import androidx.core.content.ContextCompat
import androidx.core.content.ContextCompat.getColor
import androidx.core.view.isInvisible
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
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.app.ShareViewState
import com.khmer9.lotto.base.BaseFragment
import com.khmer9.lotto.extension.*
import com.khmer9.lotto.remote.CurrentBetting
import com.khmer9.lotto.remote.SocketMessageDataModel
import com.khmer9.lotto.remote.User
import com.khmer9.lotto.remote.service.ConnectivityStates
import com.khmer9.lotto.screen.play.PlayFragment
import com.khmer9.lotto.screen.report.StatementFragment
import com.khmer9.lotto.screen.result.ResultFragment
import com.khmer9.lotto.screen.setting.SettingFragment
import com.khmer9.lotto.screen.splash.SplashScreenActivity
import com.khmer9.lotto.util.Const
import com.khmer9.lotto.util.ModelPreferencesManager
import com.khmer9.lotto.view.LottoView
import com.khmer9.lotto.view.ResultView
import com.khmer9.lotto.view.SettingButtonView
import io.reactivex.Completable
import kotlinx.android.synthetic.main.fragment_main.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import nl.dionsegijn.konfetti.models.Shape
import nl.dionsegijn.konfetti.models.Size
import org.json.JSONException
import org.json.JSONObject


/**
 * A simple [Fragment] subclass as the default destination in the navigation.
 */
class MainFragment : BaseFragment(R.layout.fragment_main) {
    private val shareViewModel = App.injectShareViewModel()
    private val sharePref = App.injectPrefHelper()

    private lateinit var adapter: MainAdapter
    private lateinit var lottoView1: LottoView
    private lateinit var lottoView2: LottoView
    private lateinit var lottoView3: LottoView
    private lateinit var lottoView4: LottoView
    private lateinit var lottoView5: LottoView
    private lateinit var lottoView6: LottoView
    private lateinit var lottoView7: LottoView
    private lateinit var lottoView8: LottoView
    private lateinit var lottoView9: LottoView
    private lateinit var lottoView10: LottoView
    private lateinit var lottoView11: LottoView
    private lateinit var lottoView12: LottoView
    private lateinit var lottoView13: LottoView
    private lateinit var lottoView14: LottoView
    private lateinit var lottoView15: LottoView
    private lateinit var lottoView16: LottoView
    private lateinit var lottoView17: LottoView
    private lateinit var lottoView18: LottoView
    private lateinit var lottoView19: LottoView
    private lateinit var lottoView20: LottoView
    private lateinit var lottoTv1: TextView
    private lateinit var lottoTv2: TextView
    private lateinit var lottoTv3: TextView
    private lateinit var lottoTv4: TextView
    private lateinit var lottoTv5: TextView
    private lateinit var lottoTv6: TextView
    private lateinit var lottoTv7: TextView
    private lateinit var lottoTv8: TextView
    private lateinit var lottoTv9: TextView
    private lateinit var lottoTv10: TextView
    private lateinit var lottoTv11: TextView
    private lateinit var lottoTv12: TextView
    private lateinit var lottoTv13: TextView
    private lateinit var lottoTv14: TextView
    private lateinit var lottoTv15: TextView
    private lateinit var lottoTv16: TextView
    private lateinit var lottoTv17: TextView
    private lateinit var lottoTv18: TextView
    private lateinit var lottoTv19: TextView
    private lateinit var lottoTv20: TextView

    private lateinit var tvResult: TextView
    private lateinit var tvResultSmall: TextView
    private lateinit var vBigSmal: ResultView
    private lateinit var vRang: ResultView
    private lateinit var ivBigLogo: ImageView
    private lateinit var lottoGroup: Group
    private lateinit var arrayLottoView: ArrayList<LottoView>
    private lateinit var arrayLottoTextView: ArrayList<TextView>
    private lateinit var user: User
    private var resultLength: Int = 0
    private var lottoAnimationDrawable: AnimationDrawable? = null
    private lateinit var btnPlay: SettingButtonView
    private lateinit var btnPlayFrame: View
    private lateinit var betPlease: MediaPlayer
    private lateinit var betTouch: MediaPlayer
    private lateinit var countDown: MediaPlayer
    private lateinit var countDown1: MediaPlayer
    private lateinit var countDown2: MediaPlayer
    private lateinit var countDown3: MediaPlayer
    private lateinit var countDown4: MediaPlayer
    private lateinit var countDown5: MediaPlayer
    private lateinit var countDown6: MediaPlayer
    private lateinit var countDown7: MediaPlayer
    private lateinit var countDown8: MediaPlayer
    private lateinit var countDown9: MediaPlayer
    private lateinit var countDown10: MediaPlayer
    private lateinit var congrat: MediaPlayer


    private lateinit var goodLuck: MediaPlayer
    lateinit var result: MediaPlayer
    private var bgDefaultLotto: Drawable? = null
    private var bgBlueLotto: Drawable? = null
    private var bgGreenLotto: Drawable? = null
    private var bgPinkLotto: Drawable? = null
    private var bgYellowLotto: Drawable? = null
    private var bgWhiteLotto: Drawable? = null

    private var bgCircleBlue: Drawable? = null
    private var bgCircleRed: Drawable? = null
    private var bgCircleGreen: Drawable? = null
    private var bgCircleYellow: Drawable? = null
    private var bgCirclePink: Drawable? = null

    private var textBig: Drawable? = null
    private var textSmall: Drawable? = null
    private var colorWhite: Int? = null
    private var colorRed: Int? = null

    private var anim: AlphaAnimation?= null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //companyInfoId =arguments?.getInt(COM_INTO_ID_KEY) ?: 0
        (requireActivity() as ShareActivity).apply {
            betPlease = MediaPlayer.create(this, R.raw.betplease)
            betTouch = MediaPlayer.create(this, R.raw.bettouch)
            countDown = MediaPlayer.create(this, R.raw.countdown)
            goodLuck = MediaPlayer.create(this, R.raw.goodluck)
            result = MediaPlayer.create(this, R.raw.result)
            countDown1 = MediaPlayer.create(this, R.raw.countdown)
            countDown2 = MediaPlayer.create(this, R.raw.countdown)
            countDown3 = MediaPlayer.create(this, R.raw.countdown)
            countDown4 = MediaPlayer.create(this, R.raw.countdown)
            countDown5 = MediaPlayer.create(this, R.raw.countdown)
            countDown6 = MediaPlayer.create(this, R.raw.countdown)
            countDown7 = MediaPlayer.create(this, R.raw.countdown)
            countDown8 = MediaPlayer.create(this, R.raw.countdown)
            countDown9 = MediaPlayer.create(this, R.raw.countdown)
            countDown10 = MediaPlayer.create(this, R.raw.countdown)
            congrat = MediaPlayer.create(this, R.raw.cong)
            user = userShare



        }

        bgDefaultLotto = ContextCompat.getDrawable(requireContext(), R.drawable.ic_logo)
        bgBlueLotto = ContextCompat.getDrawable(requireContext(), R.drawable.ic_blue_circle)
        bgPinkLotto = ContextCompat.getDrawable(requireContext(), R.drawable.ic_pink_circle)
        bgYellowLotto = ContextCompat.getDrawable(requireContext(), R.drawable.ic_yellow_circle)
        bgGreenLotto = ContextCompat.getDrawable(requireContext(), R.drawable.ic_green_circle)
        bgWhiteLotto = ContextCompat.getDrawable(requireContext(), R.drawable.bg_circle_white)

        bgCircleBlue = ContextCompat.getDrawable(requireContext(), R.drawable.bg_circle_blue_stroke)
        bgCircleRed = ContextCompat.getDrawable(requireContext(), R.drawable.bg_circle_red_stroke)
        bgCirclePink = ContextCompat.getDrawable(requireContext(), R.drawable.bg_circle_pink_stroke)
        bgCircleYellow =
            ContextCompat.getDrawable(requireContext(), R.drawable.bg_circle_yellow_stroke)
        bgCircleGreen =
            ContextCompat.getDrawable(requireContext(), R.drawable.bg_circle_green_stroke)

        textBig = ContextCompat.getDrawable(requireContext(), R.drawable.text_main_big)
        textSmall = ContextCompat.getDrawable(requireContext(), R.drawable.text_main_small)


        colorWhite = getColor(requireContext(), R.color.color_white)
        colorRed = getColor(requireContext(), R.color.color_red_600)

        anim = AlphaAnimation(0.0f, 1.0f)
        anim?.duration = 50 //You can manage the blinking time with this parameter
        anim?.startOffset = 50
        anim?.repeatMode = Animation.REVERSE
        anim?.repeatCount = Animation.INFINITE
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        (requireActivity() as ShareActivity).apply {
            userNameTextView.text = user.userName

        }

        shareViewModel.getConnectivityStates.observe(viewLifecycleOwner, Observer {
            getSocketConectionStatus(it)
        })
        shareViewModel.getLottoMessage.observe(viewLifecycleOwner, Observer {
            getLottoMessage(it)
        })
        shareViewModel.getBettingCreated.observe(viewLifecycleOwner, Observer {
            getOtherCreatedBetting(it)
        })

        shareViewModel.getShareState.observe(viewLifecycleOwner, Observer {
            getMain(it)
        })


        lottoView1 = view.findViewById(R.id.v1)
        lottoView2 = view.findViewById(R.id.v2)
        lottoView3 = view.findViewById(R.id.v3)
        lottoView4 = view.findViewById(R.id.v4)
        lottoView5 = view.findViewById(R.id.v5)
        lottoView6 = view.findViewById(R.id.v6)
        lottoView7 = view.findViewById(R.id.v7)
        lottoView8 = view.findViewById(R.id.v8)
        lottoView9 = view.findViewById(R.id.v9)
        lottoView10 = view.findViewById(R.id.v10)
        lottoView11 = view.findViewById(R.id.v11)
        lottoView12 = view.findViewById(R.id.v12)
        lottoView13 = view.findViewById(R.id.v13)
        lottoView14 = view.findViewById(R.id.v14)
        lottoView15 = view.findViewById(R.id.v15)
        lottoView16 = view.findViewById(R.id.v16)
        lottoView17 = view.findViewById(R.id.v17)
        lottoView18 = view.findViewById(R.id.v18)
        lottoView19 = view.findViewById(R.id.v19)
        lottoView20 = view.findViewById(R.id.v20)

        lottoTv1 = view.findViewById(R.id.tv1)
        lottoTv2 = view.findViewById(R.id.tv2)
        lottoTv3 = view.findViewById(R.id.tv3)
        lottoTv4 = view.findViewById(R.id.tv4)
        lottoTv5 = view.findViewById(R.id.tv5)
        lottoTv6 = view.findViewById(R.id.tv6)
        lottoTv7 = view.findViewById(R.id.tv7)
        lottoTv8 = view.findViewById(R.id.tv8)
        lottoTv9 = view.findViewById(R.id.tv9)
        lottoTv10 = view.findViewById(R.id.tv10)
        lottoTv11 = view.findViewById(R.id.tv11)
        lottoTv12 = view.findViewById(R.id.tv12)
        lottoTv13 = view.findViewById(R.id.tv13)
        lottoTv14 = view.findViewById(R.id.tv14)
        lottoTv15 = view.findViewById(R.id.tv15)
        lottoTv16 = view.findViewById(R.id.tv16)
        lottoTv17 = view.findViewById(R.id.tv17)
        lottoTv18 = view.findViewById(R.id.tv18)
        lottoTv19 = view.findViewById(R.id.tv19)
        lottoTv20 = view.findViewById(R.id.tv20)

        arrayLottoView = arrayListOf(
            lottoView1,
            lottoView2,
            lottoView3,
            lottoView4,
            lottoView5,
            lottoView6,
            lottoView7,
            lottoView8,
            lottoView9,
            lottoView10,
            lottoView11,
            lottoView12,
            lottoView13,
            lottoView14,
            lottoView15,
            lottoView16,
            lottoView17,
            lottoView18,
            lottoView19,
            lottoView20
        )

        arrayLottoTextView = arrayListOf(
            lottoTv1,
            lottoTv2,
            lottoTv3,
            lottoTv4,
            lottoTv5,
            lottoTv6,
            lottoTv7,
            lottoTv8,
            lottoTv9,
            lottoTv10,
            lottoTv11,
            lottoTv12,
            lottoTv13,
            lottoTv14,
            lottoTv15,
            lottoTv16,
            lottoTv17,
            lottoTv18,
            lottoTv19,
            lottoTv20
        )

        tvResult = view.findViewById(R.id.tv_result_show)
        tvResultSmall = view.findViewById(R.id.tv_result_number)
        ivBigLogo = view.findViewById(R.id.iv_big_logo)
        lottoGroup = view.findViewById(R.id.group_lotto)
        vBigSmal = view.findViewById(R.id.v_big_small)
        vRang = view.findViewById(R.id.v_range)

        btnPlay = view.findViewById(R.id.btn_play)
        btnPlayFrame = view.findViewById(R.id.v_frame_play)

        btnPlay.setOnClickListener {
            if (!sharePref.getIsMute()) betTouch.start()
            it.btnClick().subscribe {

                (requireActivity() as? ShareActivity)?.apply {
                    supportFragmentManager.beginTransaction()
                        .setCustomAnimations(
                            R.anim.slide_in,
                            R.anim.slide_out,
                            R.anim.slide_in_exit,
                            R.anim.slide_out_exit
                        )
                        .add(R.id.container, PlayFragment().apply {
                            arguments =
                                Bundle().apply {
                                    // putInt(Fragment7.COM_INFO_ID_KEY, companyInfoId)
                                }

                        })
                        .addToBackStack(null)
                        .commit()
                }
            }
        }
        view.findViewById<SettingButtonView>(R.id.btn_result).setOnClickListener {
            if (!sharePref.getIsMute()) betTouch.start()
            it.btnClick().subscribe {
                (requireActivity() as? ShareActivity)?.apply {
                    supportFragmentManager.beginTransaction()
                        .setCustomAnimations(
                            R.anim.slide_in,
                            R.anim.slide_out,
                            R.anim.slide_in_exit,
                            R.anim.slide_out_exit
                        )
                        .add(R.id.container, ResultFragment().apply {
                            arguments =
                                Bundle().apply {
                                    // putInt(Fragment7.COM_INFO_ID_KEY, companyInfoId)
                                }

                        })
                        .addToBackStack(null)
                        .commit()
                }
            }

        }
        (requireActivity() as? ShareActivity)?.apply {
            groupToolbarIcons.isVisible = true

            settingImageView.setOnClickListener {
                if (!sharePref.getIsMute()) betTouch.start()
                it.btnClick().subscribe {
                    supportFragmentManager.beginTransaction()
                        .setCustomAnimations(
                            R.anim.slide_in,
                            R.anim.slide_out,
                            R.anim.slide_in_exit,
                            R.anim.slide_out_exit
                        )
                        .add(R.id.container, SettingFragment())
                        .addToBackStack(null)
                        .commit()
                }

            }

            refreshImageView.setOnClickListener {
                shareViewModel.remoteMainScreenAPI(userId = user.id)
            }

            reportImageView.setOnClickListener {
                if (!sharePref.getIsMute()) betTouch.start()
                it.btnClick().subscribe {
                    supportFragmentManager.beginTransaction()
                        .setCustomAnimations(
                            R.anim.slide_in,
                            R.anim.slide_out,
                            R.anim.slide_in_exit,
                            R.anim.slide_out_exit
                        )
                        .add(R.id.container, StatementFragment().apply {
                            arguments =
                                Bundle().apply {
                                    // putInt(Fragment7.COM_INFO_ID_KEY, companyInfoId)
                                }

                        })
                        .addToBackStack(null)
                        .commit()
                }


            }
        }


    }

    @SuppressLint("CheckResult")
    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        //viewModel = ViewModelProvider(this).get(MainViewModel::class.java)


    }

    private fun animateSmallLogo() {
        GlobalScope.launch(Dispatchers.Main) {
            var i = 0
            while (i < 20) {
                arrayLottoTextView[i].background = bgDefaultLotto
                arrayLottoTextView[i].waitingLotto().subscribe()
                i++
                delay(5)
            }
        }
    }


    private fun animateLottoView(lottoTextView: TextView, number: Int): Completable {
        return Completable.create {
            lottoTextView.setBackgroundResource(R.drawable.spin_animation)
            lottoAnimationDrawable = lottoTextView.background as AnimationDrawable

            lottoAnimationDrawable!!.start()

            GlobalScope.launch(Dispatchers.Main) {
                var i = 0
                while (i < 12) {
                    val rdns = (1..80).random()
                    lottoTextView.text = "$rdns"

                    i++
                    delay(100)
                    if (i == 12) {
                        when (number) {

                            in 1..20 -> {
                                lottoTextView.background = bgBlueLotto
                            }
                            in 21..40 -> {
                                lottoTextView.background = bgYellowLotto

                            }
                            in 41..60 -> {
                                lottoTextView.background = bgPinkLotto
                            }
                            else -> {
                                lottoTextView.background = bgGreenLotto

                            }

                        }
                        lottoTextView.setText("$number")
                        it.onComplete()

                    }

                }
            }

        }


    }


    private fun animateALotto(lottoTextView: TextView, number: Int): Completable {
        return animateLottoView(lottoTextView, number)
            .andThen(animateLottoZoom(lottoTextView))
    }


    private fun animateLottoZoom(view: View): Completable {
        return view.zoomIn()
    }

    override fun onDestroyView() {
        super.onDestroyView()

    }

    override fun onResume() {
        super.onResume()
    }

    fun getOtherCreatedBetting(createBettingJsonObject: JSONObject){

        try {
            val accountBalances = createBettingJsonObject.getString("accountBalances")
            val createdJsonObject = createBettingJsonObject.getJSONObject("objCurrentBetting")
            createdJsonObject.let {
                val currentBetting = CurrentBetting(
                    id = it.getString("_id"),
                    no = it.getString("no"),
                    setId = it.getString("set_result_id"),
                    typeOfBetting = it.getString("type_of_betting"),
                    category = it.getString("category"),
                    userId = it.getString("user_id"),
                    date = it.getString("date"),
                    amount = it.getString("amount"),
                    cast = it.getString("cast"),
                    win_lose = null,
                    amount_win = null

                )
                shareViewModel.addOtherCreatedBetting(accountBalances, currentBetting)

            }


        }catch (exception: JSONException){
            exception.printStackTrace()
        }


    }
    @SuppressLint("ResourceAsColor", "CheckResult", "SetTextI18n")
    fun getLottoMessage(loto: SocketMessageDataModel) {

        if (loto.isCountDowning()) {

            when (loto.countDown) {
                1 -> if (!sharePref.getIsMute()) countDown1.start()
                2 -> if (!sharePref.getIsMute()) countDown2.start()
                3 -> if (!sharePref.getIsMute()) countDown3.start()
                4 -> if (!sharePref.getIsMute()) countDown4.start()
                5 -> if (!sharePref.getIsMute()) countDown5.start()
                6 -> if (!sharePref.getIsMute()) countDown6.start()
                7 -> if (!sharePref.getIsMute()) countDown7.start()
                8 -> if (!sharePref.getIsMute()) countDown8.start()
                9 -> if (!sharePref.getIsMute()) countDown9.start()
                10 -> if (!sharePref.getIsMute()) countDown10.start()


            }
            when (loto.countDown) {
                in 1..8 -> {

                    if (lottoGroup.isInvisible) lottoGroup.isVisible = true
                    if (ivBigLogo.isVisible) ivBigLogo.isInvisible = true
                    if (btnPlayFrame.isInvisible) {
                        btnPlayFrame.isVisible = true
                        btnPlay.isEnabled = false

                    }
                    tvResult.text = "${loto.countDown}"
                    tv_game_number.text = shareViewModel.getShareState.value?.nextNo
                    colorRed?.let { tvResult.setTextColor(it) }
                    vRang.vBox.background = bgWhiteLotto
                    vRang.tvResult.text = ""
                    vBigSmal.vBox.background = bgWhiteLotto
                    vBigSmal.tvResult.background = null

                }
                9 -> {
                    if (lottoGroup.isInvisible) lottoGroup.isVisible = true
                    if (ivBigLogo.isVisible) ivBigLogo.isInvisible = true
                    if (btnPlayFrame.isInvisible) {
                        btnPlayFrame.isVisible = true
                        btnPlay.isEnabled = false

                    }
                    tvResult.text = "${loto.countDown}"
                    tv_game_number.text = shareViewModel.getShareState.value?.nextNo
                    colorRed?.let { tvResult.setTextColor(it) }
                    vRang.vBox.background = bgWhiteLotto
                    vRang.tvResult.text = ""
                    vBigSmal.vBox.background = bgWhiteLotto
                    vBigSmal.tvResult.background = null

                    ivBigLogo.slideOut(0f).doOnComplete {
                        arrayLottoTextView.forEachIndexed { _, lottoTextView ->
                            lottoTextView.background = null

                        }
                    }.andThen(lottoGroup.slideIn(0f)).subscribe {
                        animateSmallLogo()
                    }


                }
                10 -> {
                    if (lottoGroup.isInvisible) lottoGroup.isVisible = true
                    if (ivBigLogo.isVisible) ivBigLogo.isInvisible = true
                    if (btnPlayFrame.isInvisible) {
                        btnPlayFrame.isVisible = true
                        btnPlay.isEnabled = false

                    }
                    tvResult.text = "${loto.countDown}"
                    tv_game_number.text = shareViewModel.getShareState.value?.nextNo
                    colorRed?.let { tvResult.setTextColor(it) }
                    vRang.vBox.background = bgWhiteLotto
                    vRang.tvResult.text = ""
                    vBigSmal.vBox.background = bgWhiteLotto
                    vBigSmal.tvResult.background = null

                }
                0 -> {
                    if (lottoGroup.isInvisible) lottoGroup.isVisible = true
                    if (ivBigLogo.isVisible) ivBigLogo.isInvisible = true
                    if (btnPlayFrame.isInvisible) {
                        btnPlayFrame.isVisible = true
                        btnPlay.isEnabled = false
                    }
                    tvResult.text = "${loto.countDown}"
                    tv_game_number.text = shareViewModel.getShareState.value?.nextNo
                    colorRed?.let { tvResult.setTextColor(it) }
                    vRang.vBox.background = bgWhiteLotto
                    vRang.tvResult.text = ""
                    vBigSmal.vBox.background = bgWhiteLotto
                    vBigSmal.tvResult.background = null

                    tvResult.blink(1)
                    if (!sharePref.getIsMute()) goodLuck.start()

                }
                119 -> {
                    if (lottoGroup.isVisible) lottoGroup.isInvisible = true
                    if (ivBigLogo.isInvisible) ivBigLogo.isVisible = true
                    if (btnPlayFrame.isVisible) {
                        btnPlayFrame.isVisible = false
                        btnPlay.isEnabled = true
                    }
                    colorWhite?.let { tvResult.setTextColor(it) }
                    arrayLottoTextView.forEachIndexed { _, lottoTextView ->
                        lottoTextView.background = bgDefaultLotto
                        lottoTextView.text = ""

                    }
                    //show big logo
                    lottoGroup.slideOut(0f).andThen(ivBigLogo.slideIn(0f)).subscribe()//{

                }
                in 120..128 -> {
                    if (lottoGroup.isInvisible) lottoGroup.isVisible = true
                    if (ivBigLogo.isVisible) ivBigLogo.isInvisible = true
                    if (btnPlayFrame.isVisible) {
                        btnPlayFrame.isInvisible = true
                        btnPlay.isEnabled = true
                    }
                    tvResult.text = "${loto.countDown}"
                    colorWhite?.let { tvResult.setTextColor(it) }
                }
                129 -> {
                    if (lottoGroup.isInvisible) lottoGroup.isVisible = true
                    if (ivBigLogo.isVisible) ivBigLogo.isInvisible = true
                    if (ivBigLogo.isVisible) ivBigLogo.isVisible = false
                    if (!sharePref.getIsMute()) betPlease.start()
                    if (btnPlayFrame.isVisible) {
                        btnPlayFrame.isInvisible = true
                        btnPlay.isEnabled = true
                    }
                    colorWhite?.let { tvResult.setTextColor(it) }
                    //shareViewModel.remoteMainScreenAPI(userId = user.id)
                }
                else -> {
                    if (lottoGroup.isVisible) lottoGroup.isInvisible = true
                    if (ivBigLogo.isInvisible) ivBigLogo.isVisible = true
                    if (btnPlayFrame.isVisible) {
                        btnPlayFrame.isInvisible = true
                        btnPlay.isEnabled = true
                    }
                    tvResult.text = "${loto.countDown}"
                    colorWhite?.let { tvResult.setTextColor(it) }
                    tv_bonus.setText("")
                    tv_bonus.clearAnimation()

                }

            }
            //Log.d("Socket", "not release, counting:"+loto.countDown)
        } else {

            if (lottoGroup.isInvisible) lottoGroup.isVisible = true
            if (ivBigLogo.isVisible) ivBigLogo.isInvisible = true
            if (btnPlayFrame.isInvisible) {
                btnPlayFrame.isVisible = true
                btnPlay.isEnabled = false

            }
            resultLength = loto.resultArray!!.length()
            if(loto.isBonus == true){

                tv_bonus.setText("${loto.bonusNumber}(x${loto.bonusValue})")
                tv_bonus.startAnimation(anim)

                if (resultLength == 1){
                    if (!sharePref.getIsMute()) congrat.start()
                    viewKonfetti.build()
                        .addColors(Color.YELLOW, Color.GREEN, Color.MAGENTA)
                        .setDirection(0.0, 359.0)
                        .setSpeed(1f, 5f)
                        .setFadeOutEnabled(true)
                        .setTimeToLive(2000L)
                        .addShapes(Shape.Square, Shape.Circle)
                        .addSizes(Size(12))
                        .setPosition(-50f, viewKonfetti.width + 50f, -50f, -50f)
                        .streamFor(300, 5000L)
                }

            }

            var totalResult = 0
            for (i in 0 until resultLength) {
                val eachResult = loto.resultArray.getInt(i)
                totalResult += eachResult
                when (eachResult) {
                    in 1..20 -> {
                        arrayLottoTextView[i].background = bgBlueLotto
                        arrayLottoTextView[i].text = "${eachResult}"
                    }

                    in 21..40 -> {
                        arrayLottoTextView[i].background = bgYellowLotto
                        arrayLottoTextView[i].text = "${eachResult}"

                    }
                    in 41..60 -> {
                        arrayLottoTextView[i].background = bgPinkLotto
                        arrayLottoTextView[i].text = "${eachResult}"
                    }
                    else -> {
                        arrayLottoTextView[i].background = bgGreenLotto
                        arrayLottoTextView[i].text = "${eachResult}"

                    }
                }
                //Log.d("Socket", "loto Result:"+eachResult)
            }

            colorWhite?.let { tvResult.setTextColor(it) }
            vRang.vBox.background = bgWhiteLotto
            vRang.tvResult.text = ""
            vBigSmal.vBox.background = bgWhiteLotto
            vBigSmal.tvResult.background = null
            tv_game_number.text = shareViewModel.getShareState.value?.nextNo
            val index = resultLength - 1
            animateALotto(arrayLottoTextView[index], loto.resultArray.getInt(index)).subscribe {
                if (!sharePref.getIsMute()) result.start()
                animateTextView(loto.resultArray.getInt(index), totalResult, tvResult).doOnEnd {
                    if (resultLength == 20) {//last lotto
                        shareViewModel.remoteMainScreenAPI(userId = user.id)
                        shareViewModel.getLottoMessage.value?.totalValue?.let {
                            getResultSmallOrBig(it)
                            getResultRange(it)

                        }

                        tvResult.resultBlink().subscribe {
                            vBigSmal.zoomIn().subscribe()
                            vRang.zoomIn().subscribe()
                        }

                    } else if (resultLength == 1) {
                        tvResult.text = "${loto.resultArray.getInt(index)}"
                        tvResultSmall.text = "${loto.resultArray.getInt(index)}"

                    }
                }

                tvResultSmall.text = "$totalResult"


            }


        }
    }

    fun getSocketConectionStatus(status: Int) {

        when (status) {

            ConnectivityStates.STATE_DISCONNECTED -> {
                Log.d("Socket", "onDisconnect...")

                val mStartActivity = Intent(requireContext(), SplashScreenActivity::class.java)
                startActivity(mStartActivity)
                System.exit(0)


            }
            ConnectivityStates.STATE_NOT_CONNECTED -> {
                Log.d("Socket", "onNotconnected...")
                Toast.makeText(requireContext(), "មិនមាន Internet", Toast.LENGTH_LONG).show()


            }
            ConnectivityStates.STATE_RECONNECTING -> {
                Log.d("Socket", "onReconnecting...")


            }
            ConnectivityStates.STATE_TIMEOUT -> {
                Log.d("Socket", "onTimout...")
                val intent = Intent(requireContext(), SplashScreenActivity::class.java)
                startActivity(intent)
                requireActivity().finishAffinity()


            }
            ConnectivityStates.STATE_CONNECTED -> {
                Log.d("Socket", "onConnected...")
                shareViewModel.remoteMainScreenAPI(userId = user.id)
//                Handler().postDelayed(
//                    {
//                       // binding.connectivityStatusTV.setVisibility(View.GONE)
//                    },
//                    500
//                )
            }
        }

    }

    fun getMain(state: ShareViewState) {
        if (!state.myBettingList.isNullOrEmpty()) {
            adapter = MainAdapter(state.myBettingId!!)
            adapter.submitList(state.myBettingList as List<BaseListItem>?)
            rv.setHasFixedSize(true)
            rv.layoutManager = LinearLayoutManager(context)
            rv.adapter = adapter
            adapter.printButtonListener = { ticketID, gameID, betDate, betType, betCast, winLose ->
                //val item = adapter.currentList[index] as ListItem
                printSomePrintable(
                    user.userName,
                    ticketID,
                    gameID,
                    betDate,
                    betType,
                    betCast,
                    winLose
                )
            }
        }

        if (state.result != null) {
            tv_game_number.text = state.result.no
            tvResultSmall.text = state.result.totalValue
            getResultSmallOrBig(state.result.totalValue.toInt())
            getResultRange(state.result.totalValue.toInt())


        }

        if (state.accountBalance != null) {
            (requireActivity() as? ShareActivity)?.apply {

                balanceTextView.text = currencyFormat(state.accountBalance.toInt())
            }

        }

    }

    fun getResultSmallOrBig(resultNumber: Int) {
        when (resultNumber) {
            in 210..810 -> {
                vBigSmal.vBox.background = bgCircleBlue
                vBigSmal.tvResult.background = textSmall
            }
            in 811..1410 -> {
                vBigSmal.vBox.background = bgCircleRed
                vBigSmal.tvResult.background = textBig
            }

        }

    }

    fun getResultRange(resultNumber: Int) {

        when (resultNumber) {
            in 210..695 -> {
                vRang.vBox.background = bgCircleYellow
                vRang.tvResult.text = "1"
            }
            in 696..763 -> {
                vRang.vBox.background = bgCircleBlue
                vRang.tvResult.text = "2"
            }
            in 764..855 -> {
                vRang.vBox.background = bgCircleGreen
                vRang.tvResult.text = "3"
            }
            in 856..923 -> {
                vRang.vBox.background = bgCircleRed
                vRang.tvResult.text = "4"
            }
            in 924..1410 -> {
                vRang.vBox.background = bgCirclePink
                vRang.tvResult.text = "5"
            }

        }
    }

}

