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

import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.core.view.isVisible
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.ahmedelsayed.sunmiprinterutill.PrintMe
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.remote.User
import com.sambath.klaklouk_main.util.PrefHelper
import kotlinx.android.synthetic.*
import kotlinx.android.synthetic.main.fragment_current_bets.*
import java.text.DecimalFormat

class CurrentBetsFragment : BaseFragment(R.layout.fragment_current_bets) {
    private val shareViewModel = App.injectShareViewModel()
    private lateinit var adapter: CurrentBetsAdapter
    private lateinit var user: User
    private lateinit var sharePref: PrefHelper
    private lateinit var currency: String
    private lateinit var printMe: PrintMe
    private val df = DecimalFormat("###,###.##")
    private lateinit var currentBetsViewModel: CurrentBetsViewModel
    private lateinit var totalAmount: String

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        sharePref = App.injectPrefHelper()
        (requireActivity() as ShareActivity).apply {
            user = userShare
        }
        currentBetsViewModel = CurrentBetsViewModel(App.injectApiService(), App.injectPrefHelper())
        when (user.currencyType) {
            1 -> {//dollar
                currency = "$"
            }
            2 -> {//riel
                currency = "៛"
            }
            3 -> {//baht
                currency = "฿"
            }
        }
        printMe = PrintMe(context)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        currentBetsViewModel.getCurrentBetsData()
        (requireActivity() as ShareActivity).apply {
            refreshImageView.setOnClickListener {
                currentBetsViewModel.getCurrentBetsData()
            }
        }
        adapter = CurrentBetsAdapter()
        val layoutBlueManager = LinearLayoutManager(requireActivity() as? ShareActivity)
        rv_current_bet.layoutManager = layoutBlueManager
        rv_current_bet.itemAnimator = DefaultItemAnimator()
        rv_current_bet.adapter = adapter
        adapter.printButtonListener =
            { fightNo, betDate, betType, amount, payout, payoutPrint, id ->
                val nums = payoutPrint.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 {
                    payoutPrint
                }
                if (Printooth.hasPairedPrinter()) {
                    printCfPrintable(
                        user,
                        fightNo,
                        betDate,
                        betType,
                        amount,
                        payoutPrint,
                        totalAmount,
                        id,
                        sharePref.getChannelType()
                    )
                } else {
                    val views = layoutInflater.inflate(R.layout.invoice_print, null)
                    views.findViewById<MaterialTextView>(R.id.title).text = betType
                    views.findViewById<MaterialTextView>(R.id.channel).text =
                        sharePref.getChannelType().toString()
//                    views.findViewById<MaterialTextView>(R.id.betId).text = getLastFourChars(id, 4)
                    views.findViewById<MaterialTextView>(R.id.fightNo).text = fightNo
                    views.findViewById<MaterialTextView>(R.id.account).text = user.userName
                    views.findViewById<MaterialTextView>(R.id.betType).text = betType
                    views.findViewById<MaterialTextView>(R.id.date).text = betDate
                    views.findViewById<MaterialTextView>(R.id.currencyType).text = currency
                    views.findViewById<MaterialTextView>(R.id.betPoint).text = payoutPrint
                    views.findViewById<MaterialTextView>(R.id.cast).text = totalAmount
                    /*val nums = payoutPrint.split("x", ":")
                    if (nums.size > 1) {
                        val cast = nums[0].trim().toFloatOrNull()
                        val pay = nums[1].trim().toFloatOrNull()
                        val total = cast?.let { (it * pay!!).plus(it) }
                        views.findViewById<MaterialTextView>(R.id.payout).text =
                            (df.format(total) + currency)
                    } else {
                        views.findViewById<MaterialTextView>(R.id.payout).text = payoutPrint
                    }*/

                    printMe.sendViewToPrinter(views)
                }
            }
        label_amount.text = "Amount ($currency)"
        currentBetsViewModel.state.observe(viewLifecycleOwner, androidx.lifecycle.Observer {
            Log.d("dataxzsd", "data live" + it.currentBetData)
            getCurrentBets(it)
            it.currentBetData?.let { it1 -> shareViewModel.setCurrentBettingData(it1) }
        })
        shareViewModel.getUpdateFlagMain.observe(viewLifecycleOwner, Observer {
            if (it) {
//                Log.d("dataxzsdup", "update data live")
                currentBetsViewModel.getCurrentBetsData()
                shareViewModel.setUpdateFlagMain(false)
            }
        })
        shareViewModel.getDefinedResultAndChannel.observe(viewLifecycleOwner, Observer {
            currentBetsViewModel.getCurrentBetsData()
        })
    }

    private fun getCurrentBets(it: CurrentBetsViewState) {
//        Log.d("callApi", "current report")
        progressCurrentBets.isVisible = it.isProgress
        if (it.currentBetData?.item != null) {
//            Log.d("callApi", "currentBetsList")
            adapter.submitList(it.currentBetData?.item)
        }
        adapter.notifyDataSetChanged()
    }

    companion object {
        private const val ARG_SECTION_NUMBER = "section_number"

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

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