package com.khmer9.yuki.screen.play

import android.annotation.SuppressLint
import android.media.MediaPlayer
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.widget.AppCompatButton
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import com.ahmedelsayed.sunmiprinterutill.PrintMe
import com.google.android.material.textview.MaterialTextView
import com.khmer9.yuki.R
import com.khmer9.yuki.app.App
import com.khmer9.yuki.app.ShareActivity
import com.khmer9.yuki.app.ShareViewState
import com.khmer9.yuki.base.BaseFragment
import com.khmer9.yuki.extension.btnClick
import com.khmer9.yuki.remote.LottoSet
import com.khmer9.yuki.remote.SocketMessageDataModel
import com.khmer9.yuki.remote.User
import com.khmer9.yuki.remote.main.SocketClientTimeDataModel
import com.khmer9.yuki.util.Const
import com.khmer9.yuki.util.ModelPreferencesManager
import com.khmer9.yuki.util.PrefHelper
import com.khmer9.yuki.view.CircleView
import com.mazenrashed.printooth.Printooth
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.Moshi
import kotlinx.android.synthetic.main.fragment_play.*
import kotlinx.android.synthetic.main.view_circle.view.*

/**
 * A simple [Fragment] subclass as the second destination in the navigation.
 */
class PlayFragment : BaseFragment(R.layout.fragment_play) {
    private lateinit var tvBettingType: TextView
    private lateinit var tvAmount: TextView
    private val shareViewModel = App.injectShareViewModel()
    private lateinit var betTouch: MediaPlayer
    private lateinit var user: User
    private lateinit var btnOk: Button
    private var totalAmount: Int = 0
    private lateinit var lottoSet: LottoSet
    private val prefHelper = App.injectPrefHelper()
    private lateinit var printMe: PrintMe
    private lateinit var lottoSetList: List<LottoSet>
    private val lottoSetListBetting: MutableList<LottoSet> = mutableListOf()
    private lateinit var moshi: Moshi

    private lateinit var putMoney: MediaPlayer
    private lateinit var betSuccess: MediaPlayer

    private lateinit var sharePref: PrefHelper

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        lottoSetList = ModelPreferencesManager.getList(Const.LOTTO_KEY)!!
        printMe = PrintMe(context)
        (requireActivity() as ShareActivity).apply {
            betTouch = MediaPlayer.create(this, R.raw.bettouch)
            user = loginData.user!!
        }

        sharePref = App.injectPrefHelper()
        putMoney = MediaPlayer.create(requireContext(), R.raw.put_bet_amount)
        betSuccess = MediaPlayer.create(requireContext(), R.raw.bet_success_2)
        moshi = Moshi.Builder().build()
    }

    @SuppressLint("CheckResult")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        (requireActivity() as? ShareActivity)?.apply {
            refreshImageView.setOnClickListener {
            }

            shareViewModel.getClientTime.observe(viewLifecycleOwner, Observer {
                if (!it.isNullOrEmpty()) {
                    val adapter: JsonAdapter<SocketClientTimeDataModel> = moshi.adapter(
                        SocketClientTimeDataModel::class.java
                    )
                    val socketClientTimeResponse = adapter.fromJson(it)
                    try {
                        if (socketClientTimeResponse != null) {
                            if (socketClientTimeResponse.isCountdown) {
                                onBackPressed()
                            }
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
            })
            shareViewModel.getShareState.observe(viewLifecycleOwner, Observer {
                getPlay(it)
            })
            groupToolbarIcons.isVisible = false
        }

        tvAmount = view.findViewById(R.id.tv_amount_play)
        tvBettingType = view.findViewById(R.id.tv_game_number_big_small)
        view.findViewById<AppCompatButton>(R.id.btn_close).setOnClickListener {
            if (!sharePref.getIsMute()) betTouch.start()
            it.btnClick().subscribe {
                (requireActivity() as? ShareActivity)?.apply {
                    onBackPressed()
                }
            }
        }

        btnOk = view.findViewById<Button>(R.id.btn_ok)
        btnOk.setOnClickListener {
            if (!sharePref.getIsMute()) betTouch.start()
            //val date = formatShowDate(Date())
            it.btnClick().subscribe {
                val minValue = sharePref.getMinBetting()
                val maxValue = sharePref.getMaxBetting()
                if (totalAmount in minValue..maxValue) {
                    try {
                        if (tvBettingType.text.isNotEmpty()) {
                            confirmBet(lottoSetListBetting, totalAmount)
                            /*shareViewModel.remoteCreateBettingAPI(lottoSet, totalAmount)
                            //Create betting and call the betting current api
                            //shareViewModel.remoteBettingCurrentMobileAPI()
                            totalAmount = 0
                            tvAmount.text = ""
                            tvBettingType.text = ""*/
                        } else Toast.makeText(requireContext(), "សូមជ្រើសរើសភ្នាល់", Toast.LENGTH_LONG).show()
                    } catch (e: java.lang.Exception) {
                        e.printStackTrace()
                    }
                } else {
                    val message = "ទឹកប្រាក់ភ្នាល់ត្រូវនៅចន្លោះ $minValue ទៅ $maxValue"
                    putMoney.start()
                    Toast.makeText(requireContext(), message, Toast.LENGTH_LONG).show()
                }
            }
        }

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

        view.findViewById<ImageView>(R.id.tv_clear).setOnClickListener {
            if (!sharePref.getIsMute()) betTouch.start()
            it.btnClick().subscribe {
                totalAmount = 0
                tvAmount.text = ""
                tvBettingType.text = ""
            }
        }

        //-----------------------------------------------------------------
        if (user.currencyType == 1) {
            v_1k.tv_value.text = "1"
            v_1k.iv_logo.setImageResource(R.drawable.text_dollar)

            v_2k.tv_value.text = "2"
            v_2k.iv_logo.setImageResource(R.drawable.text_dollar)

            v_5k.tv_value.text = "5"
            v_5k.iv_logo.setImageResource(R.drawable.text_dollar)

            v_10k.tv_value.text = "10"
            v_10k.iv_logo.setImageResource(R.drawable.text_dollar)

            v_20k.tv_value.text = "20"
            v_20k.iv_logo.setImageResource(R.drawable.text_dollar)

            v_50k.tv_value.text = "50"
            v_50k.iv_logo.setImageResource(R.drawable.text_dollar)

            v_100k.tv_value.text = "100"
            v_100k.iv_logo.setImageResource(R.drawable.text_dollar)

            v_200k.tv_value.text = "200"
            v_200k.iv_logo.setImageResource(R.drawable.text_dollar)
        } else if (user.currencyType == 2) {
            v_1k.tv_value.text = "1K"
            v_1k.iv_logo.isVisible = false

            v_2k.tv_value.text = "2K"
            v_2k.iv_logo.isVisible = false

            v_5k.tv_value.text = "5K"
            v_5k.iv_logo.isVisible = false

            v_10k.tv_value.text = "10K"
            v_10k.iv_logo.isVisible = false

            v_20k.tv_value.text = "20K"
            v_20k.iv_logo.isVisible = false

            v_50k.tv_value.text = "50K"
            v_50k.iv_logo.isVisible = false

            v_100k.tv_value.text = "100K"
            v_100k.iv_logo.isVisible = false

            v_200k.tv_value.text = "200K"
            v_200k.iv_logo.isVisible = false
        }

        view.findViewById<CircleView>(R.id.v_1k).setOnClickListener {
            if (!sharePref.getIsMute()) betTouch.start()
            it.btnClick().subscribe {
                if (user.currencyType == 1) {
                    totalAmount = if (tvAmount.text.toString().trim().isBlank()) {
                        1
                    } else {
                        val amount = tvAmount.text.toString().replace(",", "").toInt()
                        amount + 1
                    }
                } else if (user.currencyType == 2) {
                    totalAmount = if (tvAmount.text.toString().trim().isBlank()) {
                        1000
                    } else {
                        val amount = tvAmount.text.toString().replace(",", "").toInt()
                        amount + 1000
                    }
                }

                tvAmount.text = currencyFormat(totalAmount)
            }
        }
        view.findViewById<CircleView>(R.id.v_2k).setOnClickListener {
            if (!sharePref.getIsMute()) betTouch.start()

            it.btnClick().subscribe {
                if (user.currencyType == 1) {
                    totalAmount = if (tvAmount.text.toString().trim().isBlank()) {
                        2
                    } else {
                        val amount = tvAmount.text.toString().replace(",", "").toInt()
                        amount + 2
                    }
                } else if (user.currencyType == 2) {
                    totalAmount = if (tvAmount.text.toString().trim().isBlank()) {
                        2000
                    } else {
                        val amount = tvAmount.text.toString().replace(",", "").toInt()
                        amount + 2000
                    }
                }

                tvAmount.text = currencyFormat(totalAmount)
            }
        }

        view.findViewById<CircleView>(R.id.v_5k).setOnClickListener {
            if (!sharePref.getIsMute()) betTouch.start()
            it.btnClick().subscribe {
                if (user.currencyType == 1) {
                    totalAmount = if (tvAmount.text.toString().trim().isBlank()) {
                        5
                    } else {
                        val amount = tvAmount.text.toString().replace(",", "").toInt()
                        amount + 5
                    }
                } else if (user.currencyType == 2) {
                    totalAmount = if (tvAmount.text.toString().trim().isBlank()) {
                        5000
                    } else {
                        val amount = tvAmount.text.toString().replace(",", "").toInt()
                        amount + 5000
                    }
                }

                tvAmount.text = currencyFormat(totalAmount)
            }
        }

        view.findViewById<CircleView>(R.id.v_10k).setOnClickListener {
            if (!sharePref.getIsMute()) betTouch.start()
            it.btnClick().subscribe {
                if (user.currencyType == 1) {
                    totalAmount = if (tvAmount.text.toString().trim().isBlank()) {
                        10
                    } else {
                        val amount = tvAmount.text.toString().replace(",", "").toInt()
                        amount + 10
                    }
                } else if (user.currencyType == 2) {
                    totalAmount = if (tvAmount.text.toString().trim().isBlank()) {
                        10000
                    } else {
                        val amount = tvAmount.text.toString().replace(",", "").toInt()
                        amount + 10000
                    }
                }

                tvAmount.text = currencyFormat(totalAmount)
            }
        }

        view.findViewById<CircleView>(R.id.v_20k).setOnClickListener {
            if (!sharePref.getIsMute()) betTouch.start()

            it.btnClick().subscribe {
                if (user.currencyType == 1) {
                    totalAmount = if (tvAmount.text.toString().trim().isBlank()) {
                        20
                    } else {
                        val amount = tvAmount.text.toString().replace(",", "").toInt()
                        amount + 20
                    }
                } else if (user.currencyType == 2) {
                    totalAmount = if (tvAmount.text.toString().trim().isBlank()) {
                        20000
                    } else {
                        val amount = tvAmount.text.toString().replace(",", "").toInt()
                        amount + 20000
                    }
                }

                tvAmount.text = currencyFormat(totalAmount)
            }
        }

        view.findViewById<CircleView>(R.id.v_50k).setOnClickListener {
            if (!sharePref.getIsMute()) betTouch.start()
            it.btnClick().subscribe {
                if (user.currencyType == 1) {
                    totalAmount = if (tvAmount.text.toString().trim().isBlank()) {
                        50
                    } else {
                        val amount = tvAmount.text.toString().replace(",", "").toInt()
                        amount + 50
                    }
                } else if (user.currencyType == 2) {
                    totalAmount = if (tvAmount.text.toString().trim().isBlank()) {
                        50000
                    } else {
                        val amount = tvAmount.text.toString().replace(",", "").toInt()
                        amount + 50000
                    }
                }

                tvAmount.text = currencyFormat(totalAmount)
            }
        }

        view.findViewById<CircleView>(R.id.v_100k).setOnClickListener {
            if (!sharePref.getIsMute()) betTouch.start()
            it.btnClick().subscribe {
                if (user.currencyType == 1) {
                    totalAmount = if (tvAmount.text.toString().trim().isBlank()) {
                        100
                    } else {
                        val amount = tvAmount.text.toString().replace(",", "").toInt()
                        amount + 100
                    }
                } else if (user.currencyType == 2) {
                    totalAmount = if (tvAmount.text.toString().trim().isBlank()) {
                        100000
                    } else {
                        val amount = tvAmount.text.toString().replace(",", "").toInt()
                        amount + 100000
                    }
                }

                tvAmount.text = currencyFormat(totalAmount)
            }
        }

        view.findViewById<CircleView>(R.id.v_200k).setOnClickListener {
            if (!sharePref.getIsMute()) betTouch.start()
            it.btnClick().subscribe {
                if (user.currencyType == 1) {
                    totalAmount = if (tvAmount.text.toString().trim().isBlank()) {
                        200
                    } else {
                        val amount = tvAmount.text.toString().replace(",", "").toInt()
                        amount + 200
                    }
                } else if (user.currencyType == 2) {
                    totalAmount = if (tvAmount.text.toString().trim().isBlank()) {
                        200000
                    } else {
                        val amount = tvAmount.text.toString().replace(",", "").toInt()
                        amount + 200000
                    }
                }

                tvAmount.text = currencyFormat(totalAmount)
            }
        }

        //-------------------------------------------------------------------------------

        betPair.setOnClickListener {
            if (!sharePref.getIsMute()) betTouch.start()
            it.btnClick().subscribe {
                Log.d("betClick", "betPair")
                //tvBettingType.text = "គូ"
                lottoSet = findLottoSet(lottoSetList, "គូ")
                lottoSet.isClick = !lottoSet.isClick

                if (lottoSet.isClick) {
                    betPair.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_purple_800))
                } else {
                    betPair.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_blue_600))
                }

                setBettingData(lottoSet)
            }
        }
        betOdd.setOnClickListener {
            if (!sharePref.getIsMute()) betTouch.start()
            it.btnClick().subscribe {
                Log.d("betClick", "betOdd")
                //tvBettingType.text = "សេស"
                lottoSet = findLottoSet(lottoSetList, "សេស")
                lottoSet.isClick = !lottoSet.isClick

                if (lottoSet.isClick) {
                    betOdd.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_purple_800))
                } else {
                    betOdd.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_light_blue))
                }

                setBettingData(lottoSet)
            }
        }
        betBlue.setOnClickListener {
            if (!sharePref.getIsMute()) betTouch.start()
            it.btnClick().subscribe {
                //tvBettingType.text = "ខៀវ"
                lottoSet = findLottoSet(lottoSetList, "ខៀវ")
                lottoSet.isClick = !lottoSet.isClick

                if (lottoSet.isClick) {
                    betBlue.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_purple_800))
                } else {
                    betBlue.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_blue_800))
                }

                setBettingData(lottoSet)
            }
        }
        betRed.setOnClickListener {
            if (!sharePref.getIsMute()) betTouch.start()
            it.btnClick().subscribe {
                //tvBettingType.text = "ក្រហម"
                lottoSet = findLottoSet(lottoSetList, "ក្រហម")
                lottoSet.isClick = !lottoSet.isClick

                if (lottoSet.isClick) {
                    betRed.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_purple_800))
                } else {
                    betRed.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_red_800))
                }

                setBettingData(lottoSet)
            }
        }
        betOne.setOnClickListener {
            if (!sharePref.getIsMute()) betTouch.start()
            it.btnClick().subscribe {
                //tvBettingType.text = "ជូត"
                lottoSet = findLottoSet(lottoSetList, "ជូត")
                lottoSet.isClick = !lottoSet.isClick

                if (lottoSet.isClick) {
                    betOneTv.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_purple_800))
                } else {
                    betOneTv.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_blue_800))
                }

                setBettingData(lottoSet)
            }
        }
        betTwo.setOnClickListener {
            if (!sharePref.getIsMute()) betTouch.start()
            it.btnClick().subscribe {
                //tvBettingType.text = "ឆ្លូវ"
                lottoSet = findLottoSet(lottoSetList, "ឆ្លូវ")
                lottoSet.isClick = !lottoSet.isClick

                if (lottoSet.isClick) {
                    betTwoTv.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_purple_800))
                } else {
                    betTwoTv.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_blue_800))
                }

                setBettingData(lottoSet)
            }
        }
        betThree.setOnClickListener {
            if (!sharePref.getIsMute()) betTouch.start()
            it.btnClick().subscribe {
                //tvBettingType.text = "ខាល"
                lottoSet = findLottoSet(lottoSetList, "ខាល")
                lottoSet.isClick = !lottoSet.isClick

                if (lottoSet.isClick) {
                    betThreeTv.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_purple_800))
                } else {
                    betThreeTv.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_blue_800))
                }

                setBettingData(lottoSet)
            }
        }
        betFour.setOnClickListener {
            if (!sharePref.getIsMute()) betTouch.start()
            it.btnClick().subscribe {
                //tvBettingType.text = "ថោះ"
                lottoSet = findLottoSet(lottoSetList, "ថោះ")
                lottoSet.isClick = !lottoSet.isClick

                if (lottoSet.isClick) {
                    betFourTv.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_purple_800))
                } else {
                    betFourTv.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_red_800))
                }

                setBettingData(lottoSet)
            }
        }
        betFive.setOnClickListener {
            if (!sharePref.getIsMute()) betTouch.start()
            it.btnClick().subscribe {
                //tvBettingType.text = "រោង"
                lottoSet = findLottoSet(lottoSetList, "រោង")
                lottoSet.isClick = !lottoSet.isClick

                if (lottoSet.isClick) {
                    betFiveTv.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_purple_800))
                } else {
                    betFiveTv.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_red_800))
                }

                setBettingData(lottoSet)
            }
        }
        betSix.setOnClickListener {
            if (!sharePref.getIsMute()) betTouch.start()
            it.btnClick().subscribe {
                //tvBettingType.text = "ម្សាញ់"
                lottoSet = findLottoSet(lottoSetList, "ម្សាញ់")
                lottoSet.isClick = !lottoSet.isClick

                if (lottoSet.isClick) {
                    betSixTv.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_purple_800))
                } else {
                    betSixTv.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_red_800))
                }

                setBettingData(lottoSet)
            }
        }
        betSeven.setOnClickListener {
            if (!sharePref.getIsMute()) betTouch.start()
            it.btnClick().subscribe {
                //tvBettingType.text = "មមី"
                lottoSet = findLottoSet(lottoSetList, "មមី")
                lottoSet.isClick = !lottoSet.isClick

                if (lottoSet.isClick) {
                    betSevenTv.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_purple_800))
                } else {
                    betSevenTv.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_blue_800))
                }

                setBettingData(lottoSet)
            }
        }
        betEight.setOnClickListener {
            if (!sharePref.getIsMute()) betTouch.start()
            it.btnClick().subscribe {
                //tvBettingType.text = "មមែ"
                lottoSet = findLottoSet(lottoSetList, "មមែ")
                lottoSet.isClick = !lottoSet.isClick

                if (lottoSet.isClick) {
                    betEightTv.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_purple_800))
                } else {
                    betEightTv.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_blue_800))
                }

                setBettingData(lottoSet)
            }
        }
        betNine.setOnClickListener {
            if (!sharePref.getIsMute()) betTouch.start()
            it.btnClick().subscribe {
                //tvBettingType.text = "វក"
                lottoSet = findLottoSet(lottoSetList, "វក")
                lottoSet.isClick = !lottoSet.isClick

                if (lottoSet.isClick) {
                    betNineTv.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_purple_800))
                } else {
                    betNineTv.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_blue_800))
                }

                setBettingData(lottoSet)
            }
        }
        betTen.setOnClickListener {
            if (!sharePref.getIsMute()) betTouch.start()
            it.btnClick().subscribe {
                //tvBettingType.text = "រកា"
                lottoSet = findLottoSet(lottoSetList, "រកា")
                lottoSet.isClick = !lottoSet.isClick

                if (lottoSet.isClick) {
                    betTenTv.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_purple_800))
                } else {
                    betTenTv.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_red_800))
                }

                setBettingData(lottoSet)
            }
        }
        betEleven.setOnClickListener {
            if (!sharePref.getIsMute()) betTouch.start()
            it.btnClick().subscribe {
                //tvBettingType.text = "ច"
                lottoSet = findLottoSet(lottoSetList, "ច")
                lottoSet.isClick = !lottoSet.isClick

                if (lottoSet.isClick) {
                    betElevenTv.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_purple_800))
                } else {
                    betElevenTv.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_red_800))
                }

                setBettingData(lottoSet)
            }
        }
        betTwelve.setOnClickListener {
            if (!sharePref.getIsMute()) betTouch.start()
            it.btnClick().subscribe {
                //tvBettingType.text = "កុរ"
                lottoSet = findLottoSet(lottoSetList, "កុរ")
                lottoSet.isClick = !lottoSet.isClick

                if (lottoSet.isClick) {
                    betTwelveTv.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_purple_800))
                } else {
                    betTwelveTv.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_red_800))
                }

                setBettingData(lottoSet)
            }
        }
        betThin.setOnClickListener {
            if (!sharePref.getIsMute()) betTouch.start()
            it.btnClick().subscribe {
                //tvBettingType.text = "ស្តើង"
                lottoSet = findLottoSet(lottoSetList, "ស្តើង")
                lottoSet.isClick = !lottoSet.isClick

                if (lottoSet.isClick) {
                    betThin.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_purple_800))
                } else {
                    betThin.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_yellow_800))
                }

                setBettingData(lottoSet)
            }
        }
        betThick.setOnClickListener {
            if (!sharePref.getIsMute()) betTouch.start()
            it.btnClick().subscribe {
                //tvBettingType.text = "ក្រាស់"
                lottoSet = findLottoSet(lottoSetList, "ក្រាស់")
                lottoSet.isClick = !lottoSet.isClick

                if (lottoSet.isClick) {
                    betThick.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_purple_800))
                } else {
                    betThick.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_green_800))
                }

                setBettingData(lottoSet)
            }
        }
        bet123.setOnClickListener {
            if (!sharePref.getIsMute()) betTouch.start()
            it.btnClick().subscribe {
                //tvBettingType.text = "1-2-3"
                lottoSet = findLottoSet(lottoSetList, "1-2-3")
                lottoSet.isClick = !lottoSet.isClick

                if (lottoSet.isClick) {
                    bet123.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_purple_800))
                } else {
                    bet123.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_blue_800))
                }

                setBettingData(lottoSet)
            }
        }
        bet456.setOnClickListener {
            if (!sharePref.getIsMute()) betTouch.start()
            it.btnClick().subscribe {
                //tvBettingType.text = "4-5-6"
                lottoSet = findLottoSet(lottoSetList, "4-5-6")
                lottoSet.isClick = !lottoSet.isClick

                if (lottoSet.isClick) {
                    bet456.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_purple_800))
                } else {
                    bet456.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_red_800))
                }

                setBettingData(lottoSet)
            }
        }
        bet789.setOnClickListener {
            if (!sharePref.getIsMute()) betTouch.start()
            it.btnClick().subscribe {
                //tvBettingType.text = "7-8-9"
                lottoSet = findLottoSet(lottoSetList, "7-8-9")
                lottoSet.isClick = !lottoSet.isClick

                if (lottoSet.isClick) {
                    bet789.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_purple_800))
                } else {
                    bet789.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_blue_800))
                }

                setBettingData(lottoSet)
            }
        }
        bet101112.setOnClickListener {
            if (!sharePref.getIsMute()) betTouch.start()
            it.btnClick().subscribe {
                //tvBettingType.text = "10-11-12"
                lottoSet = findLottoSet(lottoSetList, "10-11-12")
                lottoSet.isClick = !lottoSet.isClick

                if (lottoSet.isClick) {
                    bet101112.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_purple_800))
                } else {
                    bet101112.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_red_800))
                }

                setBettingData(lottoSet)
            }
        }
    }

    private fun currencyType(): String {
        when (user.currencyType) {
            1 -> {//dollar
                return "$"
            }
            2 -> {//riel
                return "៛"
            }
            3 -> {//baht
                return "฿"
            }
        }
        return ""
    }

    private fun resetBettingUi() {
        lottoSetListBetting.clear()

        for (item in lottoSetList) {
            item.isClick = false
        }

        betPair.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_blue_600))
        betOdd.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_light_blue))
        betBlue.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_blue_800))
        betRed.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_red_800))
        betOneTv.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_blue_800))
        betTwoTv.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_blue_800))
        betThreeTv.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_blue_800))
        betFourTv.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_red_800))
        betFiveTv.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_red_800))
        betSixTv.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_red_800))
        betSevenTv.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_blue_800))
        betEightTv.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_blue_800))
        betNineTv.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_blue_800))
        betTenTv.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_red_800))
        betElevenTv.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_red_800))
        betTwelveTv.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_red_800))
        betThin.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_yellow_800))
        betThick.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_green_800))
        bet123.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_blue_800))
        bet456.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_red_800))
        bet789.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_blue_800))
        bet101112.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_red_800))
    }

    private fun setBettingData(lottoSet: LottoSet) {
        if (lottoSetListBetting != null) {
            val item = lottoSetListBetting.contains(lottoSet)
            if (item) {
                lottoSetListBetting.remove(lottoSet)
            } else {
                lottoSetListBetting += lottoSet
            }
        } else {
            lottoSetListBetting += lottoSet
        }

        var bettings = ""
        for (item in lottoSetListBetting) {
            bettings += item.typeOfBetting + " "
        }
        tvBettingType.text = bettings
    }

    private fun confirmBet(listBettings: MutableList<LottoSet>, amount: Int) {
        val total = amount * listBettings.count()

        var bettings = ""
        for (item in lottoSetListBetting) {
            bettings += item.typeOfBetting + " "
        }

        val builder = context?.let { AlertDialog.Builder(it) }
        builder?.setTitle(getString(R.string.confirm_betting))
        builder?.setMessage(getString(R.string.confirm_betting_2) + " $total ${currencyType()} " + getString(R.string.on) + "$bettings!")

        //performing positive action
        builder?.setPositiveButton(getString(R.string.yes)) { dialogInterface, which ->
            totalAmount = 0
            tvAmount.text = ""
            tvBettingType.text = ""
            dialogInterface.dismiss()
        }
        //performing negative action
        builder?.setNegativeButton(getString(R.string.cancel)) { dialogInterface, which ->
            dialogInterface.dismiss()
        }
        // Create the AlertDialog
        val alertDialog: AlertDialog? = builder?.create()
        // Set other dialog properties
        alertDialog?.setCancelable(false)
        alertDialog?.show()
    }

    private fun printInvoice(it: ShareViewState?) {
        if (it != null) {
            if (it.isBetSuccess) {
                betSuccess.start()
                resetBettingUi()

                val betItem = it.createBettingData
                Toast.makeText(requireContext(), "ការភ្នាល់របស់អ្នកបានសំរេច!", Toast.LENGTH_SHORT).show()
                if (prefHelper.getIsAutoPrint()) {
                    if (Printooth.hasPairedPrinter()) {
                        if (betItem != null) {
                            try {
                                val strSplit = betItem.amount.split("x")
                                val strSplit2 = strSplit[1].split("=")
                                val bet = strSplit[0].trim()
                                val cast = strSplit2[0].trim()
                                val winLost = bet.toDouble() * cast.toDouble()

                                printSomePrintable(
                                    user.userName,
                                    betItem.no.toString(),
                                    betItem.id,
                                    betItem.time,
                                    "",
                                    betItem.amount,
                                    winLost.toString()
                                )
                            } catch (e: Exception) {
                                printSomePrintable(
                                    user.userName,
                                    betItem.no.toString(),
                                    betItem.id,
                                    betItem.time,
                                    "",
                                    betItem.amount,
                                    "0"
                                )
                            }
                        }
                    } else {
                        val views = layoutInflater.inflate(R.layout.invoice_print, null)
                        views.findViewById<MaterialTextView>(R.id.title).text = user.userName
                        if (betItem != null) {
                            views.findViewById<MaterialTextView>(R.id.ticketId).text = betItem.no.toString()
                            views.findViewById<MaterialTextView>(R.id.gameId).text = betItem.id
                            views.findViewById<MaterialTextView>(R.id.date).text = betItem.time
                            views.findViewById<MaterialTextView>(R.id.betType).text = ""
                            views.findViewById<MaterialTextView>(R.id.betPoint).text = betItem.amount

                            try {
                                Log.d("MainListViewHolder2", betItem.amount)
                                val strSplit = betItem.amount.split("x")
                                val strSplit2 = strSplit[1].split(":")
                                val bet = strSplit[0].trim()
                                val cast = strSplit2[0].trim()
                                val winLost = bet.toDouble() * cast.toDouble()
                                views.findViewById<MaterialTextView>(R.id.winLose).text = winLost.toString()
                            } catch (e: Exception) {
                                views.findViewById<MaterialTextView>(R.id.winLose).text = "0"
                            }

                            printMe.sendViewToPrinter(views)
                        }
                    }
                }

                it.isBetSuccess = false
            } else {
                if (it.betError != null) Toast.makeText(requireContext(), "ការភ្នាល់មិនបានសំរេច!", Toast.LENGTH_SHORT).show()
            }
        }
    }

    private fun getPlay(state: ShareViewState) {
        if (state.accountBalance != null) {
            (requireActivity() as? ShareActivity)?.apply {
                balanceTextView.text = currencyFormat(state.accountBalance.toDouble())
            }
        }
    }

    @SuppressLint("SetTextI18n")
    fun getLottoMessage(loto: SocketMessageDataModel) {
        if (loto.isCountDowning() && loto.countDown!! <= 10) {
            (requireActivity() as? ShareActivity)?.apply {
                onBackPressed()
            }
        }

        if (!loto.isCountDowning()) {
            (requireActivity() as? ShareActivity)?.apply {
                onBackPressed()
            }
        }

        when (loto.countDown) {
            in 15 downTo 11 -> {
                btnOk.setText("OK(${loto.countDown!! - 10})")
            }
        }
    }
}
