package com.gamedog.vididin.features.zero

import android.app.Activity
import android.content.Intent
import android.view.LayoutInflater
import androidx.activity.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.GridLayoutManager
import com.ama.core.architecture.appBase.AppViewsEmptyViewModelActivity
import com.ama.core.architecture.util.AndroidUtil
import com.ama.core.architecture.util.CommonItemDecoration
import com.ama.core.architecture.util.SpUtil
import com.ama.core.architecture.util.setOnClickBatch
import com.gamedog.statisticreporter.StatisticUtil
import com.gamedog.vididin.VidiConst
import com.gamedog.vididin.VididinEvents
import com.viddin.videos.free.R
import com.gamedog.vididin.beans.ZeroBuyItem
import com.gamedog.vididin.beans.ZeroBuyResp
import com.gamedog.vididin.core.login.login.AccountManager
import com.gamedog.vididin.features.withdraw.dialogs.WithdrawSuccessDialog
import com.gamedog.vididin.features.zero.dialogs.ZeroBuyNotWinDialog
import com.gamedog.vididin.features.zero.dialogs.ZeroBuyRulesDialog
import com.gamedog.vididin.features.zero.dialogs.ZeroBuyWinDialog
import com.gamedog.vididin.manager.ZeroManager
import com.gamedog.vididin.router.Router
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import com.gamedog.vididin.netbase.Result
import kotlin.collections.contains
import com.viddin.videos.free.databinding.ActivityZerobuyBinding as ViewBinding



@AndroidEntryPoint
class ZeroBuyActivity : AppViewsEmptyViewModelActivity<ViewBinding>() {
    private val viewModel: ZeroBuyViewModel by viewModels()
    private lateinit var mAdapter: ZeroItemAdapter




    override fun inflateViewBinding(inflater: LayoutInflater) = ViewBinding.inflate(inflater)

    override fun ViewBinding.initViews() {
        binding.run {
            setOnClickBatch(tvZeroGoldNum, tvZeroLotteryList, llDiamondAd) {
                when (this) {
                    tvZeroGoldNum ->  {

                    }

                    tvZeroLotteryList ->  {
                        gotoLotteryRecords()
                    }

                    llDiamondAd -> {
                        gotoEarnDiamond()
                    }
                }
            }

            updateUIDiamondNum()

            titlebar.setTitleText(R.string.zero_buy)
            titlebar.addRightIcon(R.mipmap.icon_question_mark, {
                showHintInfo()
            })


            with(recyclerView) {
                mAdapter = ZeroItemAdapter({ itemId, diamondCost->

                    if (AccountManager.getDiamond() >= diamondCost) {
                        requestParticipateActivity(itemId)
                    } else {
                        AndroidUtil.showToast(R.string.dont_enought_diamond)
                    }
                })
                adapter = mAdapter
                layoutManager = GridLayoutManager(this@ZeroBuyActivity, 2)
                addItemDecoration(
                    CommonItemDecoration.create(horizontalSpace = 45, verticalSpace = 45)
                )
            }
        }


        StatisticUtil.reportEvents(StatisticUtil.KEY_lottery_Show)
    }



    override fun ViewBinding.initWindowInsets() {
        setImmerseRootView(contentRoot)
    }

    private fun showHintInfo() {
        ZeroBuyRulesDialog(this@ZeroBuyActivity).show()
    }

    override fun ViewBinding.initListeners() {
        registerEvents({ data->
            when (data?.mEventType) {
                VididinEvents.Event_Account_Diamond_Changed -> {
                    updateUIDiamondNum()
                }

                VididinEvents.EVENT_ZERO_WITHDRAW_LIST_CHANGED -> {
                    checkPreWithdrawWaitNotifyResult()
                }
            }
        }, VididinEvents.Event_Account_Diamond_Changed,
            VididinEvents.EVENT_ZERO_WITHDRAW_LIST_CHANGED)

        requestData()

        checkPreWithdrawWaitNotifyResult()
    }

    private fun checkPreWithdrawWaitNotifyResult() {
        val waitNotifyList = ZeroManager.instance().getWaitNotifyResultList()

        waitNotifyList.forEach {
            WithdrawSuccessDialog(this, cashNumStr = it.winCashNumStr).show()
            ZeroManager.instance().updateHasNotifyValue(it.purchase_id)
        }
    }

    private fun updateUIDiamondNum() {
        binding.tvZeroGoldNum.text = AccountManager.getDiamond().toString()
    }

    override fun ViewBinding.initObservers() {
        //TODO("Not yet implemented")
    }

    private fun gotoLotteryRecords() {
        Router.WinRecord.startActivity(this)
    }

    private fun gotoEarnDiamond() {
        Router.WatchAd.startActivity(this, VidiConst.WATCH_AD_FOR_ZERO_EARN_DIAMOND)
    }

    //----------------------- start -----------------------------


    private fun requestData() {
        lifecycleScope.launch {
            viewModel.ZeroBuyListData.collect { result ->
                when (result) {
                    is Result.Loading -> { showLoading(false) }
                    is Result.Success -> {
                        hideLoading()
                        updateUIs(result.data)
                    }
                    is Result.Error -> {
                        hideLoading()
                    }
                }
            }
        }

        viewModel.requestZeroBuyInfo()
    }


    private fun requestParticipateActivity(itemId: Int) {
        val joinedItemIds: List<Int> = SpUtil.instance().getList<Int>(SpUtil.KEY_ZEROBUY_JOINED_ACTIVITY_IDS)
        if (!joinedItemIds.contains(AccountManager.getAccount()?.userId)) {
            lifecycleScope.launch {
                viewModel.ZeroBuyJoinResult.collect { result ->
                    when (result) {
                        is Result.Loading -> { }
                        is Result.Success -> {
                            result.data?.let {
                                AccountManager.adjustDiamond(-1 * it.cost)
                            }

                            updateItemUI(result.data)
                        }
                        is Result.Error -> { AndroidUtil.showToast(R.string.has_join_failed_zerobuy) }
                    }
                }
            }

            viewModel.requestJoinZeroBuy(itemId)
        } else {
            AndroidUtil.showToast(R.string.has_joined_zerobuy)
        }
    }


    private fun updateUIs(data: ZeroBuyResp) {
        mAdapter.submitList(data.current_purchases)
        showCompletePurchasesInfo(data.finished_purchases)
    }

    private fun showCompletePurchasesInfo(finishedList: List<ZeroBuyItem>?) {
        finishedList?.let {
            val userId = AccountManager.getAccount().userId
            val joinedIdList = SpUtil.instance().getList<Int>(SpUtil.KEY_ZEROBUY_JOINED_ACTIVITY_IDS)
            val hasNotifiedIdList: MutableList<Int> = SpUtil.instance().getList<Int>(SpUtil.KEY_ZEROBUY_HAS_NOTIFY_IDS).toMutableList()
            it.forEach { item->
                if (joinedIdList.contains(item.id) && !hasNotifiedIdList.contains(item.id)) {
                    hasNotifiedIdList.add(item.id)

                    item.winners?.let {
                        if (it.contains(userId)) {
                            ZeroBuyWinDialog(this@ZeroBuyActivity, item).show()
                        } else {
                            ZeroBuyNotWinDialog(this@ZeroBuyActivity, item).show()
                        }
                    }
                }

                SpUtil.instance().putList(SpUtil.KEY_ZEROBUY_HAS_NOTIFY_IDS, hasNotifiedIdList)
            }
        }
    }

    private fun updateItemUI(joinedItem: ZeroBuyItem?) {
        val currentList = mAdapter.currentList.toMutableList()
        val indexToUpdate = currentList.indexOfFirst { it.id == joinedItem?.id }
        if (indexToUpdate != -1) {
            currentList.removeAt(indexToUpdate)
            currentList.add(indexToUpdate, joinedItem)
            mAdapter.submitList(currentList)
        }
    }




    //----------------------- end -----------------------------
    companion object {
        internal fun startActivity(activity: Activity) {
            activity.startActivity(Intent(activity.applicationContext, ZeroBuyActivity::class.java))
        }
    }

}