package com.gh.gamecenter.mygame

import android.content.Intent
import android.os.Build
import android.os.Bundle
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.RecyclerView
import com.gh.gamecenter.common.base.activity.BaseActivity_TabLayout
import com.gh.gamecenter.common.constant.Constants
import com.gh.common.exposure.ExposureListener
import com.gh.gamecenter.core.runOnIoThread
import com.gh.gamecenter.core.utils.SPUtils
import com.gh.common.util.UsageStatsHelper
import com.gh.gamecenter.common.utils.toColor
import com.gh.gamecenter.common.utils.toDrawable
import com.gh.gamecenter.common.view.CustomDividerItemDecoration
import com.gh.download.DownloadManager
import com.gh.gamecenter.R
import com.gh.gamecenter.common.baselist.ListAdapter
import com.gh.gamecenter.entity.GameEntity
import com.gh.gamecenter.entity.GameInstall
import com.gh.gamecenter.manager.PackagesManager
import com.gh.gamecenter.personalhome.InstalledGameDialog

class MyPlayedGameFragment : PlayedGameFragment() {

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == UsageStatsHelper.USAGE_STATUS_REQUEST_CODE && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
            if (mListRv.itemDecorationCount > 0) {
                mListRv.removeItemDecorationAt(0)
                mListRv.addItemDecoration(itemDecoration)
            }
            mAdapter?.resetListData()
            SPUtils.setBoolean(UsageStatsHelper.USAGE_STATUS_SP_KEY, UsageStatsHelper.checkForPermission())
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 提交用户使用数据
        runOnIoThread {
            UsageStatsHelper.checkAndPostUsageStats()
        }
        mCachedView.setBackgroundColor(R.color.background_white.toColor(requireContext()))
    }

    override fun provideListAdapter(): ListAdapter<GameEntity> {
        return mAdapter
            ?: PlayedGameAdapter(requireContext(), mViewModel, true).apply {
                mAdapter = this
                mExposureListener = ExposureListener(this@MyPlayedGameFragment, this)
            }
    }

    override fun onChanged(ts: MutableList<GameEntity>?) {
        super.onChanged(ts)
        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_MY_GAME, false)
        val tabCheckIndex = activity?.intent?.getIntExtra(BaseActivity_TabLayout.PAGE_INDEX, 0) ?: 0
        if (tabCheckIndex == 0 && !isCancel && ts.isNullOrEmpty() && installedList.isNotEmpty()) {
            val mDialog = InstalledGameDialog(requireContext(), installedList, "我的光环_新", "我的游戏-标记玩过弹窗")
            mDialog.show()
            mDialog.onConfirmClickListener = {
                onLoadRefresh()
            }
        }
    }

    override fun getItemDecoration(): RecyclerView.ItemDecoration {
        val notDecorateTheFirstItem =
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) !UsageStatsHelper.checkForPermission() else false
        return getItemDecoration(notDecorateTheFirstItem)
    }

    fun getItemDecoration(notDecorateTheFirstItem: Boolean): RecyclerView.ItemDecoration {
        mItemDecoration = CustomDividerItemDecoration(
            requireContext(),
            onlyDecorateTheFirstItem = false,
            notDecorateTheFirstItem = notDecorateTheFirstItem,
            notDecorateTheLastItem = true,
            notDecorateTheFirstTwoItems = false
        ).apply {
            setDrawable(R.drawable.divider_my_game.toDrawable(requireContext())!!)
        }
        return mItemDecoration
    }
}