package com.gh.gamecenter.personalhome.home.game

import android.os.Bundle
import android.view.View
import com.gh.gamecenter.common.constant.Constants
import com.gh.common.util.DialogUtils
import com.gh.gamecenter.common.constant.EntranceConsts.KEY_USER_ID
import com.gh.gamecenter.core.utils.SPUtils
import com.gh.gamecenter.common.utils.toColor
import com.gh.gamecenter.common.utils.viewModelProvider
import com.gh.common.xapk.XapkInstaller
import com.gh.common.xapk.XapkUnzipStatus
import com.gh.download.DownloadManager
import com.gh.gamecenter.R
import com.gh.gamecenter.common.baselist.ListFragment
import com.gh.gamecenter.entity.GameEntity
import com.gh.gamecenter.entity.GameInstall
import com.gh.gamecenter.eventbus.EBDownloadStatus
import com.gh.gamecenter.eventbus.EBPackage
import com.gh.gamecenter.manager.PackagesManager
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.mygame.PlayedGameViewModel
import com.gh.gamecenter.personalhome.InstalledGameDialog
import com.lightgame.download.DataWatcher
import com.lightgame.download.DownloadEntity
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

open class UserPlayedGameFragment : ListFragment<GameEntity, PlayedGameViewModel>() {

    private var mUserId = ""
    private var mAdapter: UserPlayedGameAdapter? = null
    private var mDialog: InstalledGameDialog? = null
    private val mDataWatcher = object : DataWatcher() {
        override fun onDataChanged(downloadEntity: DownloadEntity) {
            mAdapter?.notifyItemByDownload(downloadEntity)

            if (downloadEntity.meta[XapkInstaller.XAPK_UNZIP_STATUS] == XapkUnzipStatus.FAILURE.name) {
                showUnzipFailureDialog(downloadEntity)
            }
        }
    }

    override fun provideListViewModel() = viewModelProvider<PlayedGameViewModel>(PlayedGameViewModel.Factory(mUserId))

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

    override fun getItemDecoration() = null

    override fun onCreate(savedInstanceState: Bundle?) {
        mUserId = arguments?.getString(KEY_USER_ID, "") ?: ""
        super.onCreate(savedInstanceState)
        mListRv?.overScrollMode = View.OVER_SCROLL_NEVER
        mListRv?.setBackgroundColor(R.color.background_white.toColor(requireContext()))
    }

    override fun onResume() {
        if (isEverPause && mAdapter != null) mAdapter?.notifyDataSetChanged()
        super.onResume()
        DownloadManager.getInstance().addObserver(mDataWatcher)
    }


    override fun onLoadEmpty() {
        super.onLoadEmpty()

        val installedList =
            PackagesManager.filterSameApk(PackagesManager.filterDownloadBlackPackage(PackagesManager.getInstalledList()))
        val simulatorDownloadEntityList = DownloadManager.getInstance().allSimulatorDownloadEntity
        simulatorDownloadEntityList.forEach { entity ->
            installedList.add(
                GameInstall(
                    entity.gameId,
                    packageName = entity.packageName,
                    name = entity.name,
                    icon = entity.icon
                )
            )
        }
        //val count = SPUtils.getInt(Constants.SP_MARK_INSTALLED_GAME, 0)
        val isCancel = SPUtils.getBoolean(Constants.SP_MARK_INSTALLED_GAME_USER_HOME, false)
        if (mUserId == UserManager.getInstance().userId
            && !isCancel
//                && it.isNullOrEmpty()
            && installedList.isNotEmpty()
        ) {
            mDialog = InstalledGameDialog(requireContext(), installedList, "个人主页详情", "标记玩过弹窗")
            mDialog?.show()
            mDialog?.onConfirmClickListener = {
                onLoadRefresh()
            }
        }
    }

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

    // 下载被删除事件
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMainThread(status: EBDownloadStatus) {
        if ("delete" == status.status) {
            mAdapter?.notifyItemAndRemoveDownload(status)
        }
    }

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

    fun showUnzipFailureDialog(downloadEntity: DownloadEntity) {
        val data = mAdapter?.positionAndPackageMap ?: return
        for (gameAndPosition in data) {
            if (gameAndPosition.key.contains(downloadEntity.packageName)) {
                val targetView = mLayoutManager.findViewByPosition(gameAndPosition.value)
                if (targetView != null) {
                    DialogUtils.showUnzipFailureDialog(requireContext(), downloadEntity)
                    return
                }
            }
        }
    }
}