package com.gh.gamecenter.simulatorgame

import android.os.Bundle
import android.view.View
import com.gh.common.util.AdHelper
import com.gh.common.util.DirectUtils
import com.gh.common.util.NewFlatLogUtils
import com.gh.download.DownloadManager
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.utils.safelyGetInRelease
import com.gh.gamecenter.common.utils.viewModelProvider
import com.gh.gamecenter.common.utils.viewModelProviderFromParent
import com.gh.gamecenter.core.AppExecutor
import com.gh.gamecenter.common.baselist.ListFragment
import com.gh.gamecenter.common.baselist.LoadType
import com.gh.gamecenter.core.utils.MtaHelper
import com.gh.gamecenter.databinding.FragmentSimulatorGameListBinding
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.feature.entity.SimulatorEntity
import com.gh.gamecenter.game.GameAndPosition
import com.halo.assistant.HaloApp
import com.lightgame.download.DataWatcher
import com.lightgame.download.DownloadEntity

class SimulatorGameListFragment : ListFragment<GameEntity, SimulatorGameListViewModel>() {

    private lateinit var mSimulatorEntity: SimulatorEntity
    private var mAdapter: SimulatorGameListAdapter? = null
    private var mHaveLoad = false
    private lateinit var mSimulatorGameViewModel: SimulatorGameViewModel
    private var mBinding: FragmentSimulatorGameListBinding? = null

    private val dataWatcher = object : DataWatcher() {
        override fun onDataChanged(downloadEntity: DownloadEntity) {
            val data = getGameEntityByPackage(downloadEntity.packageName)
            for (gameAndPosition in data) {
                if (gameAndPosition.entity != null && gameAndPosition.entity.name == downloadEntity.name) {
                    val entryMap = gameAndPosition.entity.getEntryMap()
                    entryMap[downloadEntity.platform] = downloadEntity
                }
                mAdapter?.notifyItemChanged(gameAndPosition.position)
            }
        }

        override fun onDataInit(downloadEntity: DownloadEntity) {
            onDataChanged(downloadEntity)
        }
    }


    override fun getLayoutId() = 0

    override fun getInflatedLayout() =
        FragmentSimulatorGameListBinding.inflate(layoutInflater).apply { mBinding = this }.root

    private fun getGameEntityByPackage(packageName: String): List<GameAndPosition> {
        val positionList = ArrayList<GameAndPosition>()
        val positionMap = mListViewModel.positionAndPackageMap
        for (key in positionMap.keys) {
            if (key.contains(packageName)) {
                val position = positionMap[key]!!
                val game = mAdapter?.entityList?.safelyGetInRelease(position - 1)
                if (game != null) {
                    positionList.add(GameAndPosition(game, position))
                }
            }
        }
        return positionList
    }

    //安装、卸载事件
//    @Subscribe(threadMode = ThreadMode.MAIN)
//    fun onEventMainThread(busFour: EBPackage) {
//        if ("安装" == busFour.type || "卸载" == busFour.type) {
//            mAdapter?.notifyDataSetChanged()
//        }
//    }

    fun resetPage() {
        mAdapter?.resetPageFromFragment()
    }

    override fun getItemDecoration() = null

    override fun onCreate(savedInstanceState: Bundle?) {
        arguments?.apply {
            mSimulatorEntity = getParcelable(EntranceConsts.KEY_SIMULATOR) ?: SimulatorEntity()
        }
        super.onCreate(savedInstanceState)
        mSimulatorGameViewModel = viewModelProviderFromParent()
        mBinding?.run {
            AdHelper.getAdForLocation(AdHelper.LOCATION_SIMULATOR_GAME)?.let { ad ->
                simulatorGameLayout.run {
                    setOnClickListener {
                        MtaHelper.onEvent("广告位统计", "模拟器游戏", ad.title)
                        NewFlatLogUtils.logSimulatorGameCollectionClick()
                        DirectUtils.directToLinkPage(requireContext(), ad.toLinkEntity(), "(模拟器游戏-广告位)", "")
                    }
                }
            }
        }
    }

    override fun provideListAdapter() = mAdapter
        ?: SimulatorGameListAdapter(requireContext(), mSimulatorEntity, this).apply { mAdapter = this }


    override fun provideListViewModel(): SimulatorGameListViewModel {
        return viewModelProvider(
            SimulatorGameListViewModel.Factory(
                HaloApp.getInstance().application,
                mSimulatorEntity.type
            )
        )
    }

    override fun isAutomaticLoad() = false

    override fun onResume() {
        super.onResume()

        if (!mHaveLoad) {
            AppExecutor.uiExecutor.executeWithDelay(Runnable {
                mListViewModel.load(LoadType.NORMAL)
                mHaveLoad = true
            }, 200)
        }

        DownloadManager.getInstance().addObserver(dataWatcher)

        // 启动模拟器游戏后，返回本页面若mLaunchGameFlag为true，则刷新页面（主要是为了更新游戏item的"近期玩过"标签）
        if (mAdapter?.mLaunchGameFlag == true) {
            onLoadRefresh()
            mAdapter?.mLaunchGameFlag = false
        }
    }

    override fun onLoadDone() {
        super.onLoadDone()
        if (mSimulatorGameViewModel.isSimulatorGameFirstLoad) {
            mSimulatorGameViewModel.simulatorGameLoadSuccess.postValue(true)
            mSimulatorGameViewModel.isSimulatorGameFirstLoad = false
        }
    }

    override fun onPause() {
        super.onPause()
        DownloadManager.getInstance().removeObserver(dataWatcher)
    }

    override fun onChanged(ts: MutableList<GameEntity>?) {
        super.onChanged(ts)
        if (ts.isNullOrEmpty()) {
            mSimulatorGameViewModel.hideSpecificSimulatorTypeFromMemory(mSimulatorEntity.type)
        }
    }

    fun getFirstItemView(): View? {
        return mListRv.findViewHolderForAdapterPosition(1)?.itemView
    }
}