package com.khmer9.lotto.screen.play

import android.annotation.SuppressLint
import android.media.MediaPlayer
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.View
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.core.view.isVisible
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.gdtlib.lib.adapter.BaseListItem
import com.gdtlib.lib.viewholder.BaseListViewHolder.Companion.getCurrency
import com.gdtlib.lib.viewholder.BaseListViewHolder.Companion.getTypeOfBetting
import com.khmer9.lotto.R
import com.khmer9.lotto.app.App
import com.khmer9.lotto.extension.btnClick
import com.khmer9.lotto.app.ShareActivity
import com.khmer9.lotto.app.ShareViewState
import com.khmer9.lotto.base.BaseFragment
import com.khmer9.lotto.remote.LottoSet
import com.khmer9.lotto.remote.SocketMessageDataModel
import com.khmer9.lotto.remote.User
import com.khmer9.lotto.screen.main.MainAdapter
import com.khmer9.lotto.util.Const
import com.khmer9.lotto.util.ModelPreferencesManager
import com.khmer9.lotto.view.CircleView
import com.khmer9.lotto.view.RectangleView
import com.khmer9.lotto.view.SquareView
import kotlinx.android.synthetic.main.fragment_play.*

/**
 * A simple [Fragment] subclass as the second destination in the navigation.
 */
class PlayFragment : BaseFragment(R.layout.fragment_play) {
    private lateinit var tvPlayBigSmall: TextView
    private lateinit var tvAmount: TextView
    private val shareViewModel = App.injectShareViewModel()
    private lateinit var adapter: MainAdapter
    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 lateinit var lottoSetList : List<LottoSet>
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        lottoSetList = ModelPreferencesManager.getList(Const.LOTTO_KEY)!!
        //Log.d("Data:","---Categpru-"+lottoSetList[0].category)
        (requireActivity() as ShareActivity).apply {
            betTouch = MediaPlayer.create(this, R.raw.bettouch)
            user = userShare
           
        }


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



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

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

            }

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

            })

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

            groupToolbarIcons.isVisible=false
            tvAmount = findViewById(R.id.tv_amount_play)
            tvPlayBigSmall = findViewById(R.id.tv_game_number_big_small)

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

                it.btnClick().subscribe {
                    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) {

                        if (tvPlayBigSmall.text.isNotEmpty()) shareViewModel.remoteCreateBettingAPI(lottoSet,totalAmount, userId = user.id)
                        else Toast.makeText(applicationContext, "សូមជ្រើសរើសភ្នាល់", Toast.LENGTH_LONG).show()

                    }else {
                        val message = "ទឹកប្រាក់ភ្នាល់ត្រូវនៅចន្លោះ $minValue ទៅ $maxValue"
                        Toast.makeText(applicationContext, message, Toast.LENGTH_LONG).show()
                    }

                }

            }
            view.findViewById<ImageView>(R.id.tv_clear).setOnClickListener {
                if (!sharePref.getIsMute()) betTouch.start()

                it.btnClick().subscribe {
                    totalAmount=0
                    tvAmount.text =""
                    tvPlayBigSmall.text=""
                }

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

                it.btnClick().subscribe {
                    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 {
                    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 {
                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 {
                    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 {
                    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 {
                    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_200k).setOnClickListener {
                if (!sharePref.getIsMute()) betTouch.start()

                it.btnClick().subscribe {
                    totalAmount = if (tvAmount.text.toString().trim().isBlank()){
                        200000

                    }else{

                        val amount = tvAmount.text.toString().replace(",","").toInt()
                        amount + 200000
                    }
                    tvAmount.text=currencyFormat(totalAmount)
                }
            }
            view.findViewById<CircleView>(R.id.v_500k).setOnClickListener {
                if (!sharePref.getIsMute()) betTouch.start()

                it.btnClick().subscribe {
                    totalAmount = if (tvAmount.text.toString().trim().isBlank()){
                        500000

                    }else{

                        val amount = tvAmount.text.toString().replace(",","").toInt()
                        amount + 500000
                    }
                    tvAmount.text=currencyFormat(totalAmount)
                }
            }
            view.findViewById<RectangleView>(R.id.v_small).setOnClickListener {
                if (!sharePref.getIsMute()) betTouch.start()

                it.btnClick().subscribe {
                    tvPlayBigSmall.text = "តូច"
                    lottoSet = findLottoSet(lottoSetList,"Small")

                }
            }
            view.findViewById<RectangleView>(R.id.v_big).setOnClickListener {
                if (!sharePref.getIsMute()) betTouch.start()

                it.btnClick().subscribe {
                    tvPlayBigSmall.text = "ធំ"
                    lottoSet = findLottoSet(lottoSetList,"Large")

                }
            }
            view.findViewById<SquareView>(R.id.v_1).setOnClickListener {
                if (!sharePref.getIsMute()) betTouch.start()

                it.btnClick().subscribe {
                    tvPlayBigSmall.text = "1"
                    lottoSet = findLottoSet(lottoSetList,"1")


                }
            }
            view.findViewById<SquareView>(R.id.v_2).setOnClickListener {
                if (!sharePref.getIsMute()) betTouch.start()

                it.btnClick().subscribe {
                    tvPlayBigSmall.text = "2"
                    lottoSet = findLottoSet(lottoSetList,"2")

                }
            }
            view.findViewById<SquareView>(R.id.v_3).setOnClickListener {
                if (!sharePref.getIsMute()) betTouch.start()

                it.btnClick().subscribe {
                    tvPlayBigSmall.text = "3"
                    lottoSet = findLottoSet(lottoSetList,"3")


                }
            }
            view.findViewById<SquareView>(R.id.v_4).setOnClickListener {
                if (!sharePref.getIsMute()) betTouch.start()

                it.btnClick().subscribe {
                    tvPlayBigSmall.text = "4"
                    lottoSet = findLottoSet(lottoSetList,"4")

                }
            }
            view.findViewById<SquareView>(R.id.v_5).setOnClickListener {
                if (!sharePref.getIsMute()) betTouch.start()

                it.btnClick().subscribe {
                    tvPlayBigSmall.text = "5"
                    lottoSet = findLottoSet(lottoSetList,"5")


                }
            }
        }

    }

    private fun getPlay(state: ShareViewState) {

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

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

        }
         if (!state.myBettingList.isNullOrEmpty()) {

             adapter = MainAdapter(state.myBettingId!!)
             adapter.submitList(state.myBettingList as List<BaseListItem>?)
             rv_tb1.setHasFixedSize(true)
             rv_tb1.layoutManager = LinearLayoutManager(context)
             rv_tb1.adapter = adapter
             adapter.printButtonListener={
                     ticketID, gameID, betDate, betType, betCast, winLose->
                 printSomePrintable(user.userName,ticketID, gameID, betDate, betType, betCast, winLose)
             }

             state.isAutoPrint?.getContentIfNotHandled()?.let {isAuto->
                 totalAmount =0
                 tvAmount.text =""
                 tvPlayBigSmall.text=""
                // shareViewModel.setIsCall(false)
                 state.currentBetting?.let {
                     item ->
                     if (isAuto){

                         val betType = getTypeOfBetting(item.typeOfBetting)
                         val ticketID= item.id.substring(item.id.length-7)
                         val betCast = "${getCurrency(item.amount.toInt())}x${item.cast}"
                         val winLose = if (item.win_lose != null) { "${item.amount_win}" }else "???"

                         printSomePrintable(user.userName,ticketID, item.id, item.date, betType, betCast, winLose)

                     }
                     shareViewModel.emitCreateBetting(user.id, state.accountBalance.toString(),item)

                 }

             }

         }

    }

    @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})")
            }
        }
    }


}
