package com.seatel.mobilehall.ui.home.fragment

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.RelativeLayout
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import coil.load
import coil.transform.CircleCropTransformation
import com.android.volley.Request
import com.android.volley.VolleyError
import com.google.android.exoplayer2.ExoPlayer
import com.google.android.exoplayer2.MediaItem
import com.google.android.exoplayer2.source.ProgressiveMediaSource
import com.google.android.exoplayer2.ui.AspectRatioFrameLayout
import com.google.android.exoplayer2.upstream.DefaultDataSource
import com.google.android.exoplayer2.util.MimeTypes
import com.google.android.gms.tasks.OnCompleteListener
import com.google.firebase.messaging.FirebaseMessaging
import com.google.gson.Gson
import com.seatel.mobilehall.R
import com.seatel.mobilehall.data.network.SeatelJSONArrayRequest
import com.seatel.mobilehall.data.network.SeatelSuperRequest
import com.seatel.mobilehall.data.prefs.SeatelSharePreferences
import com.seatel.mobilehall.databinding.FragmentHomeBinding
import com.seatel.mobilehall.ui.application.MyApplication
import com.seatel.mobilehall.ui.base.fragment.BaseFragment
import com.seatel.mobilehall.ui.game.GameActivity
import com.seatel.mobilehall.ui.home.activity.BuyTopUpCardActivity
import com.seatel.mobilehall.ui.home.activity.BuyYesNumberPhaseTwoActivity
import com.seatel.mobilehall.ui.home.activity.EShopPhaseTwoActivity
import com.seatel.mobilehall.ui.home.activity.LocationShopMapActivity
import com.seatel.mobilehall.ui.home.activity.MyCartActivity
import com.seatel.mobilehall.ui.home.activity.MySubscriptionsActivity
import com.seatel.mobilehall.ui.home.activity.NotificationListActivity
import com.seatel.mobilehall.ui.home.activity.OrderPaymentSuccessActivity
import com.seatel.mobilehall.ui.home.activity.ProductServiceActivity
import com.seatel.mobilehall.ui.home.activity.PromotionActivity
import com.seatel.mobilehall.ui.home.activity.SupportActivity
import com.seatel.mobilehall.ui.home.activity.TopUpActivity
import com.seatel.mobilehall.ui.home.adapter.CategoryAdapter
import com.seatel.mobilehall.ui.home.adapter.HomeImageSliderAdapter
import com.seatel.mobilehall.ui.home.adapter.ImageSliderAdapter
import com.seatel.mobilehall.ui.home.interactor.BadgesCountInteractor
import com.seatel.mobilehall.ui.home.interactor.BannersInteractor
import com.seatel.mobilehall.ui.home.interactor.CategoryInteractor
import com.seatel.mobilehall.ui.home.model.BannersModel
import com.seatel.mobilehall.ui.home.model.CartModel
import com.seatel.mobilehall.ui.home.model.CategoryModel
import com.seatel.mobilehall.ui.home.model.HomeVideoItem
import com.seatel.mobilehall.ui.home.model.MainDataModel
import com.seatel.mobilehall.ui.home.presenter.BadgesCountPresenter
import com.seatel.mobilehall.ui.home.presenter.BannersPresenter
import com.seatel.mobilehall.ui.home.presenter.CategoryPresenter
import com.seatel.mobilehall.ui.invite_friend.InviteFriendActivity
import com.seatel.mobilehall.ui.login.activity.LoginActivity
import com.seatel.mobilehall.ui.login.model.ContactService
import com.seatel.mobilehall.ui.profile.activity.ProfileActivity
import com.seatel.mobilehall.util.AnalyticsHelper
import com.seatel.mobilehall.util.Constant
import com.seatel.mobilehall.util.Resource
import com.seatel.mobilehall.util.SeatelAlertDialog
import com.seatel.mobilehall.util.SeatelUtils
import com.seatel.mobilehall.util.lang.FirstLoginPreference
import com.seatel.mobilehall.util.manager.OrderingManager
import com.seatel.mobilehall.util.request.GetMainData
import com.seatel.mobilehall.util.viewFragmentBinding
import com.smarteist.autoimageslider.IndicatorView.animation.type.IndicatorAnimationType
import com.smarteist.autoimageslider.SliderAnimations
import com.smarteist.autoimageslider.SliderView
import org.json.JSONArray
import org.json.JSONObject

class HomeFragment : BaseFragment(), View.OnClickListener, BannersInteractor.View,
    CategoryInteractor.View, BadgesCountInteractor.View {


    private var TAG = javaClass.simpleName

    private val binding by viewFragmentBinding(
        FragmentHomeBinding::inflate
    )

    private var cartCount = MyApplication.badgeCartCount
    private var dataMainScreen: MainDataModel? = null
    private var mDialogShow: SeatelAlertDialog? = null
    private lateinit var mBottomSheet: SupportBottomSheetFragment
    private lateinit var mLayoutBalanceTotal: RelativeLayout
    private var mCountBadges: BadgesCountPresenter? = null

    private var reloadNeed: Boolean = true
    private var mChance: Int? = null
    private var player: ExoPlayer? = null
    private var token: String = ""

    private var contactService = ArrayList<ContactService>()


    lateinit var homeImageSliderAdapter: HomeImageSliderAdapter
    lateinit var categoryAdapter: CategoryAdapter


    override fun onAttach(context: Context) {
        super.onAttach(context)
        setmContext(context)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        //  setupViewModel()
        requestToken()
        playVideo()
        initPresenter()
        initEvent()
        checkLogin()
        binding.mSwipeRefreshLayout.setColorSchemeColors(resources.getColor(R.color.colorPrimary))
        binding.mSwipeRefreshLayout.setOnRefreshListener {
            playVideo()
            initPresenter()
            binding.mSwipeRefreshLayout.isRefreshing = false
            // initEvent()
            //  checkLogin()
        }

        return binding.root
    }


    private fun handleBanner(resource: Resource<List<BannersModel>>) {
        when (resource) {
            is Resource.Loading -> {}
            is Resource.Success -> resource.data?.let {
                it.run {
                    Log.d(TAG, "handleBanner: $it")
                }
            }

            is Resource.Error -> {}

        }
    }

    private fun requestToken() {
        FirebaseMessaging.getInstance().token.addOnCompleteListener(OnCompleteListener { task ->
            if (!task.isSuccessful) {
                Log.w(TAG, "Fetching FCM registration token failed", task.exception)
                return@OnCompleteListener
            }

            // Get new FCM registration token
            token = task.result
            getDataMainScreen(token)
            // Log and toast
            val msg = "FCM Registration token: $token"
            Log.d(TAG, msg)
            //  Toast.makeText(requireContext(), msg, Toast.LENGTH_SHORT).show()
        })
    }

    private fun playVideo() {

        object : SeatelJSONArrayRequest(requireContext()) {
            override fun getFunctionName(): String {
                return "video-promotion"
            }

            override fun getMethod(): Int {
                return Request.Method.GET
            }

        }.setOnErrorListener {
            Log.d("TAG::>>>", "playVideo: ${it.message}")
        }.execute {
            val movie = it as JSONArray

            for (i in 0 until movie.length()) {
                val gson = Gson().fromJson(movie[0].toString(), HomeVideoItem::class.java)


                if (gson.video.isNotEmpty()) {

                    val videoUrl = gson.video
                    val uri = Uri.parse(videoUrl)
                    binding.run {
                        player = ExoPlayer.Builder(requireContext()).build()
                        playerView.resizeMode = AspectRatioFrameLayout.RESIZE_MODE_FILL
                        imageVideoThumbnail.load(gson.thumbnail) {
                            crossfade(true)
                        }
                        imagePlayVideo.setOnClickListener {
                            imageVideoThumbnail.visibility = View.GONE
                            imagePlayVideo.visibility = View.GONE
                            player!!.playWhenReady = true
                        }
                        val mediaItem =
                            MediaItem.Builder().setUri(uri).setMimeType(MimeTypes.APPLICATION_MP4)
                                .build()
                        val mediaSource = ProgressiveMediaSource.Factory(
                            DefaultDataSource.Factory(requireContext())
                        ).createMediaSource(mediaItem)
                        player!!.apply {
                            setMediaSource(mediaSource)
                            seekTo(0, 0L)
                            prepare()
                        }.also {
                            playerView.player = it
                        }

                    }
                } else {
                    val videoUrl =
                        "http://api-dev.yes.com.kh/uploads/video-promotion/register-yes-app.mp4"
                    val uri = Uri.parse(videoUrl)
                    binding.run {
                        player = ExoPlayer.Builder(requireContext()).build()
                        imageVideoThumbnail.setImageURI(Uri.parse("http://api-dev.yes.com.kh/uploads/video-promotion/register-yes-app.png"))
                        imagePlayVideo.setOnClickListener {
                            imageVideoThumbnail.visibility = View.GONE
                            imagePlayVideo.visibility = View.GONE
                            player!!.playWhenReady = true
                        }
                        val mediaItem =
                            MediaItem.Builder().setUri(uri).setMimeType(MimeTypes.APPLICATION_MP4)
                                .build()
                        val mediaSource = ProgressiveMediaSource.Factory(
                            DefaultDataSource.Factory(requireContext())
                        ).createMediaSource(mediaItem)
                        player!!.apply {
                            setMediaSource(mediaSource)
                            seekTo(0, 0L)
                            prepare()
                        }.also {
                            playerView.player = it
                        }
                    }
                }

            }

        }


    }

    override fun onStop() {
        super.onStop()
        if (player != null) player!!.stop()
    }

    private fun checkLogin() {
        if (getPhoneLogin().isEmpty()) {
            //not login
            binding.run {
                frameStatusBalance.visibility = View.GONE
                viewLoginSignUp.visibility = View.VISIBLE
                profileName.visibility = View.GONE
                profileNumber.visibility = View.GONE
                circleProfile.setBackgroundResource(R.drawable.ic_yes_profile)
            }
        } else binding.run {
            frameStatusBalance.visibility = View.VISIBLE
            viewLoginSignUp.visibility = View.GONE
            profileName.visibility = View.VISIBLE
            profileNumber.visibility = View.VISIBLE
        }
    }

    private fun initPresenter() {
        BannersPresenter(requireActivity(), this).onGetBanners()
        CategoryPresenter(requireActivity(), this).onGetCategory(getPhoneLogin())
        mCountBadges = BadgesCountPresenter(requireActivity(), this)

    }

    private fun initEvent() {
        binding.run {
            circleProfile.setOnClickListener(this@HomeFragment)
            imageBuyNumber.setOnClickListener(this@HomeFragment)
            imageBuyTopup.setOnClickListener(this@HomeFragment)
            layoutCart.setOnClickListener(this@HomeFragment)
            layoutNoti.setOnClickListener(this@HomeFragment)
            layoutInviteFriend.setOnClickListener(this@HomeFragment)
            frameStatusBalance.setOnClickListener(this@HomeFragment)
            floatingSupportButton.setOnClickListener(this@HomeFragment)
            btnBalance.setOnClickListener(this@HomeFragment)
            btnTopUp.setOnClickListener(this@HomeFragment)
            btnNumber.setOnClickListener(this@HomeFragment)
        }
    }


    override fun onResume() {
        super.onResume()
        getDataMainScreen(token)
        checkLogin()
    }

    private fun getDataMainScreen(token: String) {
        mCountBadges?.onGetBadgesCount(getPhoneLogin())
        Log.d(TAG, "getDataMainScreenToken: $token")
        GetMainData(requireActivity(), getPhoneLogin(), token) { it ->
            if (it) {
                dataMainScreen = Gson().fromJson(
                    SeatelSharePreferences.getInstance(requireActivity())?.getMainScreenData(),
                    MainDataModel::class.java
                )
                dataMainScreen?.let { showDataMainScreen(it) }

            }

        }.execute()

    }


    private fun showDataMainScreen(dataMainScreen: MainDataModel) {

        binding.run {
            profileName.text = dataMainScreen.getCustName()
            profileNumber.text = dataMainScreen.getPhonNumber()
            circleProfile.load(dataMainScreen.getProfilePicture()) {
                crossfade(true)
                transformations(CircleCropTransformation())
                placeholder(R.drawable.ic_yes_profile)
            }

            imageBuyTopup.load(dataMainScreen.getBannerBuyTopup()) {
                crossfade(true)
            }

            imageBuyNumber.load(dataMainScreen.getBannerBuySim()) {
                crossfade(true)
            }

            var total = java.lang.String.format(
                "%.2f", SeatelUtils.convertMbToGb(dataMainScreen.getBalance()!!)
            )
            total = total.replace(",", ".")
            txtMainBalance.text = total
            txtPlanPackage.text = dataMainScreen.getPlanName()

            val strDate =
                if (TextUtils.isEmpty(dataMainScreen.getExpDate())) "" else SeatelUtils.getDateTime(
                    "yyyy-MM-dd", Constant.DATE_FORMAT_DISPLAY, dataMainScreen.getExpDate()
                )

            txtExpires.text = resources.getString(R.string.expires)
            txtExpiresVal.text = ": $strDate"
            showExpiredDate(!TextUtils.isEmpty(strDate))
            showPlanView(!TextUtils.isEmpty(dataMainScreen.getPlanName()))
            txtStatus.text = dataMainScreen.getStatus()
            if (dataMainScreen.getStatus() == "active") {
                txtStatus.setTextColor(resources.getColor(R.color.colorGreen))
            } else txtStatus.setTextColor(resources.getColor(R.color.colorRed))

            if (isPostPaidAccount()) {
                txtUnbilled.text = "Unbilled amount"
                txtUnbilled.visibility = View.VISIBLE
                txtExpires.text = "Due date"
            } else {
                txtUnbilled.visibility = View.GONE
                txtExpires.text = resources.getString(R.string.expires)
            }

            if (dataMainScreen.getPlanCode() == "Airline_Plan_Subsplan" || dataMainScreen.getPlanCode() == "AirlinesPlan_Subsplan" || dataMainScreen.getPlanCode() == "Fortune_Plan_Subsplan") {
                txtExpiresVal.visibility = View.GONE
                txtExpires.visibility = View.GONE
            } else {
                txtExpiresVal.visibility = View.VISIBLE
                txtExpires.visibility = View.VISIBLE
            }


        }

       dataMainScreen.getContactService().forEach {
           contactService.add(it)
       }

        // Show alert force update and complete info after buy sim
        if (dataMainScreen.getIsNewUpdateAvailable()) {
            showAlertForceUpdate()
        } else if (dataMainScreen.getOrderIdUnSuccess().size > 0) {
            if (mDialogShow != null) mDialogShow?.dimissDialog()
            mDialogShow = SeatelAlertDialog.with(
                requireContext(), getString(R.string.message_input_register_info_buySim)
            ).setCancelable(false).setPositiveButton(getString(R.string.register_now)) { _, _ ->
                OrderingManager.getInstance().clear()
                val cartsModels = ArrayList<CartModel>()
                val model = CartModel()
                model.type = "sim-card"
                model.isSelected = true
                cartsModels.add(model)
                OrderingManager.getInstance().cartsModels.addAll(cartsModels)
                OrderPaymentSuccessActivity.launchInputInfo(
                    requireContext(),
                    dataMainScreen.getOrderIdUnSuccess()[0].toString(),
                    true,
                    dataMainScreen.getOrderIdUnSuccess()
                )
            }.show()
        }
    }

    private fun showExpiredDate(isShow: Boolean) {
        binding.layoutBalanceTotal.visibility = if (isShow) View.VISIBLE else View.INVISIBLE
    }

    private fun showPlanView(isShow: Boolean) {
        binding.txtPlanPackage.visibility = if (isShow) View.VISIBLE else View.INVISIBLE
        binding.checkbox.visibility = if (isShow) View.VISIBLE else View.INVISIBLE
        binding.txtStatus.visibility = if (isShow) View.VISIBLE else View.INVISIBLE
    }


    private fun showAlertForceUpdate() {
        if (dataMainScreen!!.getIsNewUpdateAvailable() && dataMainScreen!!.getForceUpdate()) {
            if (mDialogShow != null) mDialogShow?.dimissDialog()
            mDialogShow = SeatelAlertDialog.with(
                requireActivity(), getString(R.string.message_available_download_new)
            ).setCancelable(false).setPositiveButton(getString(R.string.update)) { _, _ ->
                gotoPlayStore()
            }.show()
        } else if (!dataMainScreen!!.getForceUpdate() && FirstLoginPreference.getInstance(
                requireActivity()
            )?.getIsForceUpdatePreference() == false
        ) {
            if (mDialogShow != null) mDialogShow?.dimissDialog()
            mDialogShow = SeatelAlertDialog.with(
                requireActivity(), getString(R.string.message_available_download_new)
            ).setCancelable(false).setPositiveButton(getString(R.string.update)) { _, _ ->
                gotoPlayStore()
            }.setNegativeButton(getString(R.string.later)) { _, _ ->
                FirstLoginPreference.getInstance(requireActivity())
                    ?.setIsForceUpdatePreference(true)
                mDialogShow!!.dimissDialog()
            }.show()
        }

    }

    private fun gotoPlayStore() {
        val appPackageName = requireActivity().packageName
        try {
            startActivity(
                Intent(
                    Intent.ACTION_VIEW, Uri.parse("market://details?id=$appPackageName")
                )
            )
        } catch (obj: android.content.ActivityNotFoundException) {
            startActivity(
                Intent(
                    Intent.ACTION_VIEW,
                    Uri.parse("https://play.google.com/store/apps/details?id=$appPackageName")
                )
            )
        }

    }

    /*  override fun onDestroy() {
      //   binding.homeImageSlider.stopAutoCycle()
      }*/

    override fun onGetBannersSucceed(bannersList: ArrayList<BannersModel>) {
        binding.run {
            bannersList.let {
                it.run {
                    homeImageSliderAdapter = HomeImageSliderAdapter(requireContext())
                    homeImageSliderAdapter.addItem(it)
                    homeImageSlider.setSliderAdapter(homeImageSliderAdapter)
                    homeImageSlider.setIndicatorAnimation(IndicatorAnimationType.WORM)
                    homeImageSlider.autoCycleDirection = SliderView.LAYOUT_DIRECTION_INHERIT
                    homeImageSlider.setSliderTransformAnimation(SliderAnimations.SIMPLETRANSFORMATION)
                    homeImageSlider.scrollTimeInSec = 3
                    homeImageSlider.startAutoCycle()
                }
            }
        }
    }


    override fun onGetBannersFailed(error: VolleyError) {
        SeatelAlertDialog.with(requireContext(), SeatelSuperRequest.getErrorMessageFrom(error))
            .show()
    }


    override fun onGetCategorySucceed(category: ArrayList<CategoryModel>) {
        SeatelSharePreferences.getInstance(requireContext())
            ?.setHomeCategory(Gson().toJson(category))

        binding.run {

            homeRecyclerView.layoutManager =
                LinearLayoutManager(activity, LinearLayoutManager.HORIZONTAL, false)
            categoryAdapter = CategoryAdapter(requireContext(), category) {
                when (it.name) {
                    "Top Up" -> {
                        TopUpActivity.lunch(requireActivity())
                        AnalyticsHelper.logEvent(AnalyticsHelper.Event.HOME_TAP_TOP_UP, null)
                    }

                    "Packages" -> {
                        ProductServiceActivity.lunch(requireActivity())
                        //  AnalyticsHelper.logEvent(AnalyticsHelper.Event.HOME_TAP_PLAN, null)
                    }

                    "Promotion" -> {
                        PromotionActivity.lunch(requireActivity())
                        AnalyticsHelper.logEvent(AnalyticsHelper.Event.HOME_TAP_PROMOTION, null)
                    }

                    "Ehub" -> {
                        EShopPhaseTwoActivity.lunch(requireActivity())
                        //  AnalyticsHelper.logEvent(AnalyticsHelper.Event.HOME_TAP_YES_HUB, null)
                    }

                    "Yes Hub" -> {
                        LocationShopMapActivity.lunch(requireActivity())
                        AnalyticsHelper.logEvent(AnalyticsHelper.Event.HOME_TAP_YES_HUB, null)
                    }

                    "Support" -> {
                        SupportActivity.lunch(requireActivity())
                        AnalyticsHelper.logEvent(AnalyticsHelper.Event.HOME_TAP_SUPPORT, null)
                    }

                    "Ang Pao" -> {
                    }

                    "Chhoung" -> {
                        if (getPhoneLogin().isBlank() || getMainPhoneLogin().isBlank()) {
                            LoginActivity.lunch(requireContext())
                        } else GameActivity.lunch(requireContext())
                    }

                    "Point" -> {
                        Toast.makeText(requireContext(), "Coming Soon...", Toast.LENGTH_SHORT)
                            .show()
                    }
                }
                when (it.code) {
                    "chaol-chhoung" -> if (getPhoneLogin().isBlank() || getMainPhoneLogin().isBlank()) {
                        LoginActivity.lunch(requireContext())
                    } else GameActivity.lunch(requireContext())
                }
            }
            homeRecyclerView.adapter = categoryAdapter

        }

    }

    override fun onGetCategoryFailed(error: VolleyError) {
        //   SeatelAlertDialog.with(requireContext(), SeatelSuperRequest.getErrorMessageFrom(error)).show()
    }


    override fun onClick(view: View?) {
        when (view?.tag) {
            "BUYTOPUPCARD" -> {
                BuyTopUpCardActivity.lunch(requireActivity())
                AnalyticsHelper.logEvent(AnalyticsHelper.Event.HOME_TAP_BUY_TOP_UP_CART, null)
            }

            "BUYYESNUMBER" -> {
                BuyYesNumberPhaseTwoActivity.lunch(requireActivity())
                AnalyticsHelper.logEvent(AnalyticsHelper.Event.HOME_TAP_BUY_YES_NUMBER, null)
            }

            "MY_CART" -> {
                AnalyticsHelper.logEvent(AnalyticsHelper.Event.HOME_TAP_CART, null)
                if (getPhoneLogin().isEmpty()) {
                    LoginActivity.lunch(requireActivity())
                } else MyCartActivity.launch(requireActivity())
            }

            "SEEALL" -> ProductServiceActivity.lunch(requireActivity())
            "PROFILE" -> {
                AnalyticsHelper.logEvent(AnalyticsHelper.Event.HOME_TAP_PROFILE, null)
                if (getPhoneLogin().isEmpty()) {
                    LoginActivity.lunch(requireActivity())
                } else ProfileActivity.lunch(requireActivity())
            }

            "LOGIN_SIGNUP" -> LoginActivity.lunch(requireContext())
            "NOTIFICATION" -> {
                AnalyticsHelper.logEvent(AnalyticsHelper.Event.HOME_TAP_NOTIFICATION, null)
                if (getPhoneLogin().isEmpty()) {
                    LoginActivity.lunch(requireActivity())
                } else NotificationListActivity.lunch(requireActivity())
            }

            "BUTTON_SUPPORT" -> {
                mBottomSheet = SupportBottomSheetFragment(contactService)
                //   mBottomSheet.setBottomSheetView(this)
                mBottomSheet.show(
                    requireActivity().supportFragmentManager, "SupportBottomSheetFragment"
                )
            }

            "POINT" -> Toast.makeText(requireContext(), "Coming soon...", Toast.LENGTH_SHORT).show()
            "INVITED_FRI" -> {
                AnalyticsHelper.logEvent(AnalyticsHelper.Event.HOME_TAP_INVITE_FRIEND, null)
                if (getPhoneLogin().isNullOrEmpty()) {
                    LoginActivity.lunch(getmContext())
                } else InviteFriendActivity.launchForResult(requireContext())
            }

            "SUBSCRIPTION" -> {
                AnalyticsHelper.logEvent(AnalyticsHelper.Event.HOME_TAP_PLAN, null)
                MySubscriptionsActivity.lunch(requireContext())
            }

            "BUTTON_BALANCE" -> {
                AnalyticsHelper.logEvent(AnalyticsHelper.Event.HOME_TAP_PLAN, null)
                MySubscriptionsActivity.lunch(requireContext())
            }

            "BUTTON_TOP_UP" -> {
                BuyTopUpCardActivity.lunch(requireActivity())
                AnalyticsHelper.logEvent(AnalyticsHelper.Event.HOME_TAP_BUY_TOP_UP_CART, null)
            }

            "BUTTON_NUMBER" -> {
                BuyYesNumberPhaseTwoActivity.lunch(requireActivity())
                AnalyticsHelper.logEvent(AnalyticsHelper.Event.HOME_TAP_BUY_YES_NUMBER, null)
            }


        }
    }

    override fun responseCountSucceed(data: JSONObject) {
        var badgeNoti = 0
        var badgeCart = 0
        if (data.has("notificationCount")) badgeNoti = data.optInt("notificationCount")

        if (data.has("notificationCount")) {
            badgeCart = data.optInt("cartItemCount")
        }
        setBadgesCount(badgeNoti, badgeCart)
        MyApplication.badgeCartCount = badgeCart
    }

    override fun responseCountFail(error: VolleyError) {
        SeatelAlertDialog.with(requireContext(), SeatelSuperRequest.getErrorMessageFrom(error))
            .show()
    }

    private fun setBadgesCount(notificationCount: Int, cartCount: Int) {
        binding.run {
            if (notificationCount == 0) countBadgeNotification.visibility = View.GONE else {
                if (notificationCount > 99) countBadgeNotification.text =
                    "99+" else countBadgeNotification.text = notificationCount.toString() + ""
                countBadgeNotification.visibility = View.VISIBLE
                val layout: ViewGroup.LayoutParams = countBadgeNotification.getLayoutParams()
                layout.width = SeatelUtils.convertDpToPx(requireContext(), 15)
                layout.height = layout.width
                countBadgeNotification.layoutParams = layout
            }
            if (cartCount == 0) countBadgeCart.visibility = View.GONE else {
                if (cartCount > 99) countBadgeCart.text = "99+" else countBadgeCart.text =
                    cartCount.toString() + ""
                countBadgeCart.visibility = View.VISIBLE
                val layout: ViewGroup.LayoutParams = countBadgeCart.layoutParams
                layout.width = SeatelUtils.convertDpToPx(requireContext(), 15)
                layout.height = layout.width
                countBadgeCart.layoutParams = layout
            }
        }

    }

}
