package com.gh.gamecenter.savegame

import com.ethanhua.skeleton.Skeleton
import com.gh.common.util.DialogUtils
import com.gh.common.util.NewFlatLogUtils
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.HaloApp
import com.gh.gamecenter.common.baselist.LazyListFragment
import com.gh.gamecenter.common.baselist.ListAdapter
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.databinding.FragmentListBaseBinding
import com.gh.gamecenter.common.utils.toColor
import com.gh.gamecenter.common.utils.viewModelProvider
import com.gh.gamecenter.entity.GameEntity
import com.gh.gamecenter.eventbus.EBDownloadStatus
import com.gh.gamecenter.eventbus.EBPackage
import com.lightgame.download.DataWatcher
import com.lightgame.download.DownloadEntity
import com.lightgame.download.DownloadStatus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class GameArchiveListRecommendFragment : LazyListFragment<GameEntity, GameArchiveListViewModel>() {

    private var mAdapter: GameArchiveListRecommendAdapter? = null
    private lateinit var mViewModel: GameArchiveListViewModel

    private val mBinding by lazy { FragmentListBaseBinding.inflate(layoutInflater) }

    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)
            }

            if (downloadEntity.status == DownloadStatus.add) {
                NewFlatLogUtils.logCloudArchiveRecommendGameDownload(downloadEntity.gameId, downloadEntity.name)
            }
        }

        override fun onDataInit(downloadEntity: DownloadEntity) {
            mAdapter?.notifyItemByDownload(downloadEntity)
        }
    }

    override fun initRealView() {
        super.initRealView()
        mCachedView.setBackgroundColor(R.color.background_white.toColor(requireContext()))
    }

    override fun initSkeletonScreen() {
        if (mSkeletonScreenView == null) return
        mSkeletonScreen = Skeleton.bind(mSkeletonScreenView)
            .shimmer(true)
            .angle(Constants.SHIMMER_ANGLE)
            .color(R.color.skeleton_shimmer_color)
            .duration(Constants.SHIMMER_DURATION)
            .maskWidth(Constants.MASK_WIDTH)
            .gradientCenterColorWidth(Constants.GRADIENT_CENTER_COLOR_WIDTH)
            .apply {
                load(R.layout.fragment_tags_skeleton)
            }
            .show()
    }

    override fun onResume() {
        super.onResume()
        DownloadManager.getInstance().addObserver(mDataWatcher)
    }

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

    override fun onRefresh() {
        mAdapter?.clearPositionAndPackageMap()
        super.onRefresh()
    }

    // 下载被删除事件
    @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.type || "卸载" == busFour.type) {
            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
                }
            }
        }
    }

    override fun provideListAdapter(): ListAdapter<GameEntity> {
        return mAdapter ?: GameArchiveListRecommendAdapter(requireContext(), mViewModel).apply {
            mAdapter = this
        }
    }

    override fun provideListViewModel(): GameArchiveListViewModel {
        val factory = GameArchiveListViewModel.Factory(HaloApp.getInstance(), "recommend")
        mViewModel = viewModelProvider(factory)
        return mViewModel
    }

    override fun getLayoutId() = 0

    override fun getInflatedLayout() = mBinding.root

    override fun getItemDecoration() = null
}