package com.gh.gamecenter.home.skip

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.gh.gamecenter.common.base.fragment.BaseFragment
import com.gh.common.util.LogUtils
import com.gh.download.DownloadManager
import com.gh.gamecenter.common.utils.toColor
import com.gh.gamecenter.databinding.FragmentPackageSkipBinding
import com.gh.gamecenter.feature.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 org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class PackageSkipFragment : BaseFragment<Any>() {

    private lateinit var mBinding: FragmentPackageSkipBinding
    private lateinit var mAdapter: PackageSkipAdapter
    private var games: ArrayList<GameEntity> = arrayListOf()
    private var positionAndPackageMap = HashMap<String, Int>()

    override fun getLayoutId(): Int = 0

    private val dataWatcher = object : DataWatcher() {
        override fun onDataChanged(downloadEntity: DownloadEntity) {
            for (key in positionAndPackageMap.keys) {
                if (key.contains(downloadEntity.packageName) && key.contains(downloadEntity.gameId)) {
                    val position = positionAndPackageMap[key]
                    if (position != null && position < games.size) {
                        games[position].getEntryMap()[downloadEntity.platform] = downloadEntity
                        mAdapter.notifyItemChanged(position)
                    }
                }
            }
        }
    }

    override fun getInflatedLayout(): View {
        mBinding = FragmentPackageSkipBinding.inflate(LayoutInflater.from(requireContext()), null, false)
        return mBinding.root
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        games = arguments?.getParcelableArrayList<GameEntity>(GameEntity::class.java.name)
            ?: arrayListOf()
        positionAndPackageMap.clear()
        games.forEachIndexed { index, gameEntity ->
            addGamePositionAndPackage(gameEntity, index)
        }
        mBinding.normalToolbar.setNavigationOnClickListener {
            LogUtils.uploadPackageSkip("external_show", "进入首页", "", "")
            requireActivity().finish()
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mBinding.listRv.apply {
            (itemAnimator as DefaultItemAnimator).supportsChangeAnimations = false
            layoutManager = LinearLayoutManager(requireContext())
            mAdapter = PackageSkipAdapter(requireContext(), games) {
                requireActivity().finish()
            }
            adapter = mAdapter
        }
    }

    private fun addGamePositionAndPackage(game: GameEntity, position: Int) {
        var packages = ""
        for (apkEntity in game.getApk()) {
            packages += apkEntity.packageName
        }
        packages += game.simulator?.apk?.packageName
        positionAndPackageMap[packages + position + game.id] = position
        game.gameLocation = GameEntity.GameLocation.INDEX
        game.setEntryMap(DownloadManager.getInstance().getEntryMap(game.name))
    }

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

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

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

    // 下载被删除事件
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMainThread(status: EBDownloadStatus) {
        if ("delete" == status.status) {
            for (key in positionAndPackageMap.keys) {
                if (key.contains(status.packageName) && key.contains(status.gameId)) {
                    val position = positionAndPackageMap[key]
                    if (position != null && position < games.size) {
                        games[position].getEntryMap().remove(status.platform)
                        mAdapter.notifyItemChanged(position)
                    }
                }
            }
        }
    }

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        mBinding.root.setBackgroundColor(com.gh.gamecenter.common.R.color.ui_background.toColor(requireContext()))
        mBinding.normalTitle.setTextColor(com.gh.gamecenter.common.R.color.text_primary.toColor(requireContext()))
        mBinding.tipTv1.setTextColor(com.gh.gamecenter.common.R.color.text_tertiary.toColor(requireContext()))
        mBinding.tipTv2.setTextColor(com.gh.gamecenter.common.R.color.text_primary.toColor(requireContext()))
        if (::mAdapter.isInitialized) {
            mAdapter.notifyItemRangeChanged(0, mAdapter.itemCount)
        }
    }
}