package com.sambath.klaklouk_main.screen.main.cflive.betting

import android.annotation.SuppressLint
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.ahmedelsayed.sunmiprinterutill.PrintMe
import com.google.android.material.button.MaterialButton
import com.google.android.material.textview.MaterialTextView
import com.mazenrashed.printooth.Printooth
import com.sambath.klaklouk_main.R
import com.sambath.klaklouk_main.app.App
import com.sambath.klaklouk_main.app.ShareActivity
import com.sambath.klaklouk_main.base.BaseFragment
import com.sambath.klaklouk_main.extension.btnClick
import com.sambath.klaklouk_main.remote.*
import com.sambath.klaklouk_main.util.Const
import com.sambath.klaklouk_main.util.ModelPreferencesManager
import com.sambath.klaklouk_main.util.PrefHelper
import com.squareup.moshi.Moshi
import kotlinx.android.synthetic.*
import kotlinx.android.synthetic.main.app_bar.*
import kotlinx.android.synthetic.main.content_main.*
import kotlinx.android.synthetic.main.fragment_cf_betting.*
import org.json.JSONArray
import org.json.JSONObject
import java.text.DecimalFormat

class CfBetFragment : BaseFragment(R.layout.fragment_cf_betting) {
    private lateinit var btnClose: MaterialButton
    private lateinit var cfBetViewModel: CfBetViewModel
    private val shareViewModel = App.injectShareViewModel()
    private var betMin: Int = 0
    private var betMax: Int = 0
    private var channelId: String = ""
    private var betDate: String = ""

    private var tigerId: String = "615d4a899e9ab44fe23eb9db"
    private var khlokId: String = "615d4aa59e9ab44fe23eb9dd"
    private var chickenId: String = "615d5a609e9ab44fe23eba42"
    private var lobsterId: String = "635752d7ecc8b1144bb584ff"
    private var crabId: String = "635752ddecc8b1144bb58500"
    private var fishId: String = "635752e4ecc8b1144bb58501"

    private var betAmount: Int = 0
    private var fightNo: Int = 0
    private var walaAmount: Int = 0
    private var meronAmount: Int = 0
    private var tieAmount: Int = 0
    private var isUserEnable: Boolean = false
    private var isChannelEnable: Boolean = false
    private var isStopBetting: String = "null"
    lateinit var userShare: User
    lateinit var channelShare: ChannelData
    private lateinit var printMe: PrintMe
    private lateinit var sharePref: PrefHelper
    private var btnMaster: List<BtnData> = arrayListOf()
    private val prefHelper = App.injectPrefHelper()
    private lateinit var currency: String
    private val df = DecimalFormat("###,###.##")
    private lateinit var totalAmount: String
    private lateinit var cSet: BettingTypeData
    private lateinit var moshi: Moshi
    private var cSetList: List<BettingTypeData> = mutableListOf()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        sharePref = App.injectPrefHelper()
        moshi = Moshi.Builder().build()
        cfBetViewModel = CfBetViewModel(App.injectApiService(), App.injectPrefHelper())

        /*cSetList = ModelPreferencesManager.getCfList(Const.CF_KEY)!!
        if (cSetList.isNullOrEmpty()) {
            cfBetViewModel.getMaster()
        }*/

        cfBetViewModel.getMaster()

        ModelPreferencesManager.getUser(
            Const.USER_KEY
        )?.let {
            isUserEnable = it.readOnly
            userShare = it
        }

        ModelPreferencesManager.getChannel(
            Const.CHANNEL_KEY
        )?.let {
            isChannelEnable = it.enable
            isStopBetting = it.is_open.toString().ifEmpty {
                "null"
            }
            channelShare = it
        }
        when (userShare.currencyType) {
            1 -> {//dollar
                currency = "$"
            }
            2 -> {//riel
                currency = "៛"
            }
            3 -> {//baht
                currency = "฿"
            }
        }
        printMe = PrintMe(context)
    }

    @SuppressLint("SetTextI18n")
    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 {
                shareViewModel.setUpdateFlagMain(true)
                it.btnClick().subscribe {
                    onBackPressed()
                }
            }
            refreshImageView.setOnClickListener {
                cfBetViewModel.getBtnMaster()
                cfBetViewModel.getWeight()
            }
        }
        txtMax.text = currencyFormat(betMax) + currency
        txtMin.text = currencyFormat(betMin) + currency

        //      test user read only or not
        if (isUserEnable && isChannelEnable && isStopBetting == "true") {
            /*btnBetMeron.isEnabled = true
            btnBetWala.isEnabled = true
            btnBetTie.isEnabled = true*/
        } else {
            /*btnBetMeron.isEnabled = false
            btnBetWala.isEnabled = false
            btnBetTie.isEnabled = false*/
        }

        cfBetViewModel.getBtnMaster()
        cfBetViewModel.getWeight()
        cfBetViewModel.stateMaster.observe(viewLifecycleOwner, androidx.lifecycle.Observer {
            if (it?.isSuccess == true) {
                if (it.bettingTypeData != null) {
                    if (it.bettingTypeData.isNotEmpty()) {
                        ModelPreferencesManager.putCfList(it.bettingTypeData, Const.CF_KEY)

                        tigerId = it.bettingTypeData[0]._id
                        khlokId = it.bettingTypeData[1]._id
                        chickenId = it.bettingTypeData[2]._id
                        lobsterId = it.bettingTypeData[3]._id
                        crabId = it.bettingTypeData[4]._id
                        fishId = it.bettingTypeData[5]._id

                        tiger_title.text = "X" + it.bettingTypeData[0].payoutDisplay
                        khlok_title.text = "X" + it.bettingTypeData[1].payoutDisplay
                        chicken_title.text = "X" + it.bettingTypeData[2].payoutDisplay
                        lobster_title.text = "X" + it.bettingTypeData[3].payoutDisplay
                        crab_title.text = "X" + it.bettingTypeData[4].payoutDisplay
                        fish_title.text = "X" + it.bettingTypeData[5].payoutDisplay

                        cSetList = it.bettingTypeData
                    }
                }
            }
        })
        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) + currency
                    txtMin.text = currencyFormat(betMin) + currency
                    /*txtMeronPayout.text = it.weightData.meron?.payout
                    txtWalaPayout.text = it.weightData.wala?.payout*/
                }
            }
        })

        tiger_layout.setOnClickListener {
            createBetting(K.Tiger, cSetList[0]._id)
        }

        khlok_layout.setOnClickListener {
            createBetting(K.Khlok, cSetList[1]._id)
        }

        chicken_layout.setOnClickListener {
            createBetting(K.Chicken, cSetList[2]._id)
        }

        lobster_layout.setOnClickListener {
            createBetting(K.Lobster, cSetList[3]._id)
        }

        crab_layout.setOnClickListener {
            createBetting(K.Crab, cSetList[4]._id)
        }

        fish_layout.setOnClickListener {
            createBetting(K.Fish, cSetList[5]._id)
        }

        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.getStartCountDown.observe(viewLifecycleOwner, Observer {
            if (!it.isNullOrEmpty()) {
                val obj = JSONObject(it)
                var countDown = obj.getInt(K.CountDown)
                var type = obj.getString(K.Type)

                btnBettingTime.text = countDown.toString()

                if (type.equals(K.Close, ignoreCase = true)) {
                    btnBettingStatus.text = K.Close
                    btnBettingStatus.isEnabled = false
                } else if (type.equals(K.Open, ignoreCase = true)) {
                    btnBettingStatus.text = K.Open
                    btnBettingStatus.isEnabled = true
                }
            }
        })
        shareViewModel.getResetAmount.observe(viewLifecycleOwner, Observer {
            //Log.d("getResetAmount", "onUpdatePlayerBetting" + it)
            /*txtMeronAmount.text = "0"
            txtWalaAmount.text = "0"
            txtTieAmount.text = "0"*/
        })
        shareViewModel.getUpdateUserInfo.observe(viewLifecycleOwner, Observer {
            //Log.d("SocketCfBetFragment", "getUpdateChannelInfo" + it)
            if (!it.isNullOrEmpty()) {
                val obj = JSONObject(it)
                isUserEnable = obj.getBoolean("enable")
                if (isUserEnable && isChannelEnable && isStopBetting == "true") {
                    /*btnBetMeron.isEnabled = true
                    btnBetWala.isEnabled = true
                    btnBetTie.isEnabled = true*/
                } else {
                    /*btnBetMeron.isEnabled = false
                    btnBetWala.isEnabled = false
                    btnBetTie.isEnabled = false*/
                }
            }
        })
        shareViewModel.getChannelInfo.observe(viewLifecycleOwner, Observer {
            if (it != null) {
                channelId = it.id
                fightNo = it.fightNo
                betDate = it.date
                isChannelEnable = it.enable
                isStopBetting = it.is_open.toString().ifEmpty {
                    "null"
                }

                //layMeronPayout.visibility = View.VISIBLE
                //layWalaPayout.visibility = View.VISIBLE

                if (userShare.readOnly && isChannelEnable) {
                    when (isStopBetting) {
                        "true" -> {
                            /*btnBetMeron.isEnabled = true
                            btnBetWala.isEnabled = true
                            btnBetTie.isEnabled = true*/
                        }
                        "false" -> {
                            /*btnBetMeron.isEnabled = false
                            btnBetWala.isEnabled = false
                            btnBetTie.isEnabled = false*/
                        }
                        else -> {
                            /*btnBetMeron.isEnabled = false
                            btnBetWala.isEnabled = false
                            btnBetTie.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
                    btnBetTie.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")
                txtTieAmount.text =
                    arr.getJSONObject(userShare.currencyType - 1).getString("tie_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) + currency
                txtMin.text = currencyFormat(betMin) + currency
            }
        })
        shareViewModel.getCurrentBettingData.observe(viewLifecycleOwner, Observer {
            //Log.d("getCurrentBettingData", "onUpdatePlayerBetting" + it)
            if (it != null) {
                meronAmount = it.meron
                walaAmount = it.wala
                tieAmount = it.tie
                /*txtMeronAmount.text = meronAmount.toString()
                txtWalaAmount.text = walaAmount.toString()
                txtTieAmount.text = tieAmount.toString()*/
            }
        })
    }

    private fun confirmBet(betType: String, moneyBet: Int, type_id: String) {
        val builder = context?.let { AlertDialog.Builder(it) }
        builder?.setTitle("Confirm betting!")
        builder?.setMessage("You are betting $moneyBet ${currencyType()} on $betType!")
        builder?.setPositiveButton("Yes") { dialogInterface, which ->
            cfBetViewModel.createBetting(CreateBetting(moneyBet, type_id))
            dialogInterface.dismiss()
        }
        builder?.setNegativeButton("No") { dialogInterface, which ->
            dialogInterface.dismiss()
        }
        val alertDialog: AlertDialog? = builder?.create()
        alertDialog?.setCancelable(false)
        alertDialog?.show()
    }

    private fun btnMaster(it: BtnMasterState) {
        if (it.isSuccess) {
            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 {
        }
    }

    private fun updateInfo(it: CfBetViewState) {
        if (it.isSuccess) {
            if (it.data != null) {
                (requireActivity() as? ShareActivity)?.apply {
                    tv_amount.text = it.data.balance
                }
                betAmount = 0
                when (it.data.betting) {
                    K.Tiger -> {
                        meronAmount += it.data.betAmount
                    }
                    /*K.Wala -> {
                        walaAmount += it.data.betAmount
                    }*/
                    K.Tie -> {
                        tieAmount += it.data.betAmount
                    }
                }
                /*txtMeronAmount.text = meronAmount.toString()
                txtWalaAmount.text = walaAmount.toString()
                txtTieAmount.text = tieAmount.toString()*/
                txtMsgAmount.text = ""
                edtBettingAmount.setText("")
                txtMsgSuccess.text = "Your betting is success!"
                /*btnBetMeron.isEnabled = true
                btnBetWala.isEnabled = true
                btnBetTie.isEnabled = true*/
                it.isSuccess = false
                val nums = it.data.amount.split("x", ":")
                totalAmount = if (nums.size > 1) {
                    val cast = nums[0].trim().toFloatOrNull()
                    val pay = nums[1].trim().toFloatOrNull()
                    val total = cast?.let { (it * pay!!).plus(it) }
                    (df.format(total) + currency)
                } else {
                    it.data.amount
                }
                if (prefHelper.getIsAutoPrint()) {
                    if (Printooth.hasPairedPrinter()) {
                        printCfPrintable(
                            userShare,
                            it.data.fightNo.toString(),
                            it.data.time,
                            it.data.betting,
                            it.data.amount,
                            it.data.amount,
                            totalAmount,
                            getLastFourChars(it.data._id, 4),
                            sharePref.getChannelType()
                        )
                    } else {
                        val views = layoutInflater.inflate(R.layout.invoice_print, null)
                        views.findViewById<MaterialTextView>(R.id.title).text = it.data.betting
                        views.findViewById<MaterialTextView>(R.id.channel).text =
                            sharePref.getChannelType().toString()
                        views.findViewById<MaterialTextView>(R.id.fightNo).text =
                            it.data.fightNo.toString()
                        views.findViewById<MaterialTextView>(R.id.account).text = userShare.userName
                        views.findViewById<MaterialTextView>(R.id.betType).text = it.data.betting
                        views.findViewById<MaterialTextView>(R.id.date).text = it.data.time
                        views.findViewById<MaterialTextView>(R.id.currencyType).text = currency
                        views.findViewById<MaterialTextView>(R.id.betPoint).text = it.data.amount
                        views.findViewById<MaterialTextView>(R.id.cast).text = totalAmount

                        printMe.sendViewToPrinter(views)
                    }
                }
            }
        } else {
            if (it.error != null) {
                txtMsgAmount.text = it.error
                /*btnBetMeron.isEnabled = true
                btnBetWala.isEnabled = true
                btnBetTie.isEnabled = true*/
            }
        }
    }

    private fun createBetting(betType: String, chickenId: String) {
        txtMsgSuccess.text = ""
        txtMsgAmount.text = ""
        val moneyBet = edtBettingAmount.text.toString()
        if (moneyBet.isNotEmpty()) {
            confirmBet(betType, 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()
    }
}