package com.sambath.sbc.screen.main.cflive.Betting

import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.core.view.isVisible
import androidx.lifecycle.Observer
import com.google.android.material.button.MaterialButton
import com.google.gson.Gson
import com.sambath.sbc.R
import com.sambath.sbc.app.App
import com.sambath.sbc.app.ShareActivity
import com.sambath.sbc.base.BaseFragment
import com.sambath.sbc.extension.btnClick
import com.sambath.sbc.remote.BtnData
import com.sambath.sbc.remote.CreateBetting
import com.sambath.sbc.remote.K
import com.sambath.sbc.remote.User
import com.sambath.sbc.util.Const
import com.sambath.sbc.util.LogOutTimerUtil
import com.sambath.sbc.util.ModelPreferencesManager
import com.sambath.sbc.util.PrefHelper
import kotlinx.android.synthetic.*
import kotlinx.android.synthetic.main.app_bar.*
import kotlinx.android.synthetic.main.fragment_cf_betting.*
import org.json.JSONArray
import org.json.JSONObject

class CfBetFragment : BaseFragment(R.layout.fragment_cf_betting) {
    private lateinit var btnClose: MaterialButton
    private lateinit var cfBetViewModel: CfBetViewModel
    private val shareViewModel = App.injectShareViewModel()
    private val gson = Gson()
    private var betMin: Int = 5000
    private var betMax: Int = 500000
    private var channelId: String = ""
    private var betDate: String = ""
    private var meronId: String = "615d4a899e9ab44fe23eb9db"
    private var walaId: String = "615d4aa59e9ab44fe23eb9dd"
    private var betAmount: Int = 0
    private var fightNo: Int = 0
    private var isStopBetting: String = "null"
    lateinit var userShare: User
    private lateinit var sharePref: PrefHelper
    private var btnMaster: List<BtnData> = arrayListOf()
    private val prefHelper = App.injectPrefHelper()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        sharePref = App.injectPrefHelper()
        cfBetViewModel = CfBetViewModel(App.injectApiService(), App.injectPrefHelper())
        ModelPreferencesManager.get<User>(
            Const.USER_KEY
        )?.let {
            userShare = it
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        (requireActivity() as? ShareActivity)?.apply {
            groupToolbarIcons.isVisible = false
            btnClose = view.findViewById<MaterialButton>(R.id.btn_close)
            btnClose.setOnClickListener {
//                if (!sharePref.getIsMute()) betTouch.start()
                shareViewModel.setUpdateFlagMain(true)
                it.btnClick().subscribe {
                    onBackPressed()
                }
            }
        }
        txtMax.text = currencyFormat(betMax)
        txtMin.text = currencyFormat(betMin)
        cfBetViewModel.getMaster()
        cfBetViewModel.getBtnMaster()
//        cfBetViewModel.getWeight()
        cfBetViewModel.stateMaster.observe(viewLifecycleOwner, androidx.lifecycle.Observer {
            if (it?.isSuccess == true) {
                Log.d("stateMaster", it.toString())
                if (it.bettingTypeData != null) {
                    if (it.bettingTypeData.isNotEmpty()) {
                        meronId = it.bettingTypeData[0]._id
                        walaId = it.bettingTypeData[1]._id
                    }
                }
            }
        })
        cfBetViewModel.stateBtn.observe(viewLifecycleOwner, androidx.lifecycle.Observer {
            btnMaster(it)
        })
        cfBetViewModel.state.observe(viewLifecycleOwner, androidx.lifecycle.Observer {
            updateInfo(it)
        })
        cfBetViewModel.stateWeight.observe(viewLifecycleOwner, androidx.lifecycle.Observer {
            Log.d("stateUser", it.toString())
            if (it?.isSuccess == true) {
                if (it.weightData != null) {
                    betMin = it.weightData.amountMin
                    betMax = it.weightData.amountMax
                    txtMax.text = currencyFormat(betMax)
                    txtMin.text = currencyFormat(betMin)
                    txtMeronAmount.text = it.weightData.meron?.amount
                    txtMeronPayout.text = it.weightData.meron?.payout
                    txtWalaAmount.text = it.weightData.wala?.amount
                    txtWalaPayout.text = it.weightData.wala?.payout
                }
            }
        })
//      test user read only or not
        if (userShare.readOnly) {
            btnBetMeron.isEnabled = true
            btnBetWala.isEnabled = true
        } else {
            btnBetMeron.isEnabled = false
            btnBetWala.isEnabled = false
        }
//        Red side betting
        btnBetMeron.setOnClickListener {
            LogOutTimerUtil.resetLogoutTimer(null, null)
            createBetting(K.Meron, meronId)
        }
//        Blue side betting
        btnBetWala.setOnClickListener {
            LogOutTimerUtil.resetLogoutTimer(null, null)
            createBetting(K.Wala, walaId)
        }
        btnClear.setOnClickListener {
            betAmount = 0
            edtBettingAmount.setText("")
        }
        btnZero.setOnClickListener {
            betAmount += btnMaster[0].amount
            edtBettingAmount.setText(betAmount.toString())
        }
        btnOne.setOnClickListener {
            betAmount += btnMaster[1].amount
            edtBettingAmount.setText(betAmount.toString())
        }
        btnTwo.setOnClickListener {
            betAmount += btnMaster[2].amount
            edtBettingAmount.setText(betAmount.toString())
        }
        btnThree.setOnClickListener {
            betAmount += btnMaster[3].amount
            edtBettingAmount.setText(betAmount.toString())
        }
        btnFour.setOnClickListener {
            betAmount += btnMaster[4].amount
            edtBettingAmount.setText(betAmount.toString())
        }
        btnFive.setOnClickListener {
            betAmount += btnMaster[5].amount
            edtBettingAmount.setText(betAmount.toString())
        }
        btnSix.setOnClickListener {
            betAmount += btnMaster[6].amount
            edtBettingAmount.setText(betAmount.toString())
        }
        btnSeven.setOnClickListener {
            betAmount += btnMaster[7].amount
            edtBettingAmount.setText(betAmount.toString())
        }

        txt_clear.setOnClickListener {
            val string = edtBettingAmount.text.toString()
            if (string.isNotEmpty()) {
                edtBettingAmount.setText(string.substring(0, string.length - 1))
            }
        }
        shareViewModel.getUpdatePayout.observe(viewLifecycleOwner, Observer {
            Log.d("getUpdatePayout", "onUpdatePlayerBetting" + it)
            if (!it.isNullOrEmpty()) {
                if (isStopBetting == "true") {
                    val obj = JSONObject(it)
                    if (obj.getInt("currency_type") == userShare.currencyType) {
                        txtMeronPayout.text = obj.getString("payout_wala")
                        txtWalaPayout.text = obj.getString("payout_meron")
                    }
                }
            }
        })
        shareViewModel.getResetAmount.observe(viewLifecycleOwner, Observer {
            Log.d("getResetAmount", "onUpdatePlayerBetting" + it)
            txtMeronAmount.text = "0"
            txtWalaAmount.text = "0"
        })
        shareViewModel.getChannelInfo.observe(viewLifecycleOwner, Observer {
            if (it != null) {
                channelId = it.id
                fightNo = it.fightNo
                betDate = it.date
                isStopBetting = if (it.is_open.toString().isEmpty()) {
                    "null"
                } else {
                    it.is_open.toString()
                }
                layMeronPayout.visibility = View.VISIBLE
                layWalaPayout.visibility = View.VISIBLE
                if (userShare.readOnly) {
                    when (isStopBetting) {
                        "true" -> {
                            btnBetMeron.isEnabled = true
                            btnBetWala.isEnabled = true
                        }
                        "false" -> {
                            btnBetMeron.isEnabled = false
                            btnBetWala.isEnabled = false
                        }
                        else -> {
                            btnBetMeron.isEnabled = false
                            btnBetWala.isEnabled = false
                            layMeronPayout.visibility = View.INVISIBLE
                            layWalaPayout.visibility = View.INVISIBLE
//                            txtMeronAmount.text = currencyFormat(it.amountRed)
//                            txtWalaAmount.text = currencyFormat(it.amountBlue)
//                            txtMeronPayout.text = it.payoutRed.toString()
//                            txtWalaPayout.text = it.payoutBlue.toString()
                        }
                    }
                } else {
                    btnBetMeron.isEnabled = false
                    btnBetWala.isEnabled = false
                    if (isStopBetting == "null") {
                        layMeronPayout.visibility = View.INVISIBLE
                        layWalaPayout.visibility = View.INVISIBLE
                    }
                }
            }
        })
        shareViewModel.getUpdatePayout.observe(viewLifecycleOwner, Observer {
            Log.d("getUpdatePayout", "onUpdatePlayerBetting" + it)
            if (!it.isNullOrEmpty()) {
                val obj = JSONObject(it)
                if (userShare.currencyType == obj.getInt("currency_type")) {
                    txtMeronPayout.text = obj.getString("payout_meron")
                    txtWalaPayout.text = obj.getString("payout_wala")
                }
            }
        })
        shareViewModel.onUpdateBettingAmount.observe(viewLifecycleOwner, Observer {
            Log.d("onUpdateBettingAmount", "onUpdatePlayerBetting" + it)
            if (!it.isNullOrEmpty()) {
                val arr = JSONArray(it)
                txtMeronAmount.text =
                    arr.getJSONObject(userShare.currencyType - 1).getString("meron_amount")
                txtWalaAmount.text =
                    arr.getJSONObject(userShare.currencyType - 1).getString("wala_amount")
            }
        })
        shareViewModel.onUpdateChanelDeveloper.observe(viewLifecycleOwner, Observer {
            if (!it.isNullOrEmpty()) {
//                Log.d("getUpdateData", "onUpdateChanelDeveloper" + it)
                val obj = JSONObject(it)
                betMin = obj.getInt("amount_min")
                betMax = obj.getInt("amount_max")
                txtMax.text = currencyFormat(betMax)
                txtMin.text = currencyFormat(betMin)
            }
        })
        shareViewModel.getUpdateData.observe(viewLifecycleOwner, Observer {
            channelId = it.getString(K.ChannelId)
            fightNo = it.getInt(K.Fight_No)
            betDate = it.getString(K.date)
//            Log.d("getMain", "datalive Channel ID" + channelId)
            txtMeronAmount.text = currencyFormatKh(it.getDouble(K.CastRed))
            txtWalaAmount.text = currencyFormatKh(it.getDouble(K.CastBlue))
            txtMeronPayout.text = it.getString(K.PayoutRed)
            txtWalaPayout.text = it.getString(K.PayoutBlue)
            layMeronPayout.visibility = View.VISIBLE
            layWalaPayout.visibility = View.VISIBLE
            if (userShare.readOnly) {
                when {
                    it.getString(K.TypeOfPlay) == K.Open -> {
                        btnBetMeron.isEnabled = true
                        btnBetWala.isEnabled = true
                    }
                    it.getString(K.TypeOfPlay) == K.Close -> {
                        btnBetMeron.isEnabled = false
                        btnBetWala.isEnabled = false
                    }
                    else -> {
                        btnBetMeron.isEnabled = false
                        btnBetWala.isEnabled = false
                        layMeronPayout.visibility = View.INVISIBLE
                        layWalaPayout.visibility = View.INVISIBLE
//                        txtMeronAmount.text = amountRed
//                        txtWalaAmount.text = amountBlue
//                        txtMeronPayout.text = payoutRed
//                        txtWalaPayout.text = payoutBlue
                    }
                }
            } else {
                btnBetMeron.isEnabled = false
                btnBetWala.isEnabled = false
                if (it.getString(K.TypeOfPlay) == K.Live) {
                    layMeronPayout.visibility = View.INVISIBLE
                    layWalaPayout.visibility = View.INVISIBLE
                }
            }
            betMin = it.getInt("amount_min")
            betMax = it.getInt("amount_max")
            txtMax.text = currencyFormat(betMax)
            txtMin.text = currencyFormat(betMin)
        })
    }

    private fun confirmBet(betType: String, moneyBet: Int, chickenId: String) {
        val builder = context?.let { AlertDialog.Builder(it) }
        //set title for alert dialog
        builder?.setTitle("Confirm betting!")
        //set message for alert dialog
        builder?.setMessage("You are betting $moneyBet ${currencyType()} on $betType!")
//        builder?.setIcon(android.R.drawable.ic_dialog_alert)

        //performing positive action
        builder?.setPositiveButton("Yes") { dialogInterface, which ->

            cfBetViewModel.createBetting(CreateBetting(moneyBet, chickenId))
            dialogInterface.dismiss()
        }
        //performing negative action
        builder?.setNegativeButton("No") { dialogInterface, which ->
            btnBetMeron.isEnabled = true
            btnBetWala.isEnabled = true
            dialogInterface.dismiss()
        }
        // Create the AlertDialog
        val alertDialog: AlertDialog? = builder?.create()
        // Set other dialog properties
        alertDialog?.setCancelable(false)
        alertDialog?.show()
    }

    private fun btnMaster(it: BtnMasterState) {
        Log.d("CfCreateBetting", "api success : " + it.isSuccess)
        if (it.isSuccess) {
            Log.d("CfCreateBetting", "api success : " + it.btnData)
            if (!it.btnData.isNullOrEmpty()) {
                btnMaster = it.btnData
                btnZero.text = it.btnData[0].label
                btnOne.text = it.btnData[1].label
                btnTwo.text = it.btnData[2].label
                btnThree.text = it.btnData[3].label
                btnFour.text = it.btnData[4].label
                btnFive.text = it.btnData[5].label
                btnSix.text = it.btnData[6].label
                btnSeven.text = it.btnData[7].label
            }
        } else {
            Log.d("CfCreateBetting", "api fail : ")
        }
    }

    private fun updateInfo(it: CfBetViewState) {
        if (it.isSuccess) {
            Log.d("CfCreateBetting", "api success : " + it.data)
            if (it.data != null) {
                (requireActivity() as? ShareActivity)?.apply {
                    tv_amount.text = it.data.balance
                }
                betAmount = 0
//            if (it.channel != null) {
//                fightNo = it.channel.fightNo
//                betDate = it.channel.date
//                val obj = JSONObject()
//                obj.put(K.ChannelId, it.channel.id)
//                obj.put(K.TemId, it.channel.temId)
//                obj.put(K.AmountRed, it.channel.amountRed)
//                obj.put(K.PayoutRed, it.channel.payoutRed)
//                obj.put(K.PayoutBlue, it.channel.payoutBlue)
//                obj.put(K.AmountBlue, it.channel.amountBlue)
//                shareViewModel.emitCfCreateBetting(obj)
//            }
                if (prefHelper.getIsAutoPrint()) {
                    printCfPrintable(
                        userShare,
                        it.data.fightNo.toString(),
                        it.data.time,
                        it.data.betting,
                        it.data.amount,
                        it.data.amount,
                        it.data.amount,
                        getLastFourChars(it.data._id, 4),
                        sharePref.getChannelType()
                    )
                }
                txtMsgAmount.text = ""
                edtBettingAmount.setText("")
                txtMsgSuccess.text = "Your betting is success!"
                btnBetMeron.isEnabled = true
                btnBetWala.isEnabled = true
                it.isSuccess = false
            }
//            shareViewModel.setUpdateFlagMain(true)
        } else {
            if (it.error != null) {
                txtMsgAmount.text = it.error
                btnBetMeron.isEnabled = true
                btnBetWala.isEnabled = true
            }
//            Log.d("CfCreateBetting", "api fail : " + it.accountBalance)
        }
    }

    private fun createBetting(betType: String, chickenId: String) {
        txtMsgSuccess.text = ""
        txtMsgAmount.text = ""
        val moneyBet = edtBettingAmount.text.toString()
        if (moneyBet.isNotEmpty()) {
            btnBetMeron.isEnabled = false
            btnBetWala.isEnabled = false
            confirmBet(betType, moneyBet.toInt(), chickenId)
//            cfBetViewModel.createBetting(CreateBetting(moneyBet.toInt(), chickenId))
        } else {
            txtMsgAmount.text = "Please enter amount!"
        }
    }

    companion object {
        private const val ARG_SECTION_NUMBER = "section_number"

        @JvmStatic
        fun newInstance(sectionNumber: Int): CfBetFragment {
            return CfBetFragment().apply {
                arguments = Bundle().apply {
                    putInt(ARG_SECTION_NUMBER, sectionNumber)
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        this.clearFindViewByIdCache()
    }

    private fun getLastFourChars(str: String, n: Int): String {
        var lastChars = str
        if (lastChars.length > n) {
            lastChars = lastChars.substring(lastChars.length - n, lastChars.length)
        }
        return lastChars
    }
}