package com.gh.gamecenter.gamedetail.history

import android.graphics.drawable.InsetDrawable
import android.os.Bundle
import android.view.View
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.exposure.ExposureListener
import com.gh.common.util.NewLogUtils
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.common.baselist.ListFragment
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.utils.goneIf
import com.gh.gamecenter.common.utils.observeNonNull
import com.gh.gamecenter.common.utils.setRootBackgroundColor
import com.gh.gamecenter.common.utils.viewModelProvider
import com.gh.gamecenter.core.utils.DisplayUtils
import com.gh.gamecenter.databinding.FragmentHistoryApkListBinding
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.eventbus.EBPackage
import com.halo.assistant.HaloApp
import com.lightgame.download.DataWatcher
import com.lightgame.download.DownloadEntity
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class HistoryApkListFragment : ListFragment<GameEntity, HistoryApkListViewModel>() {

    private var mAdapter: HistoryApkListAdapter? = null
    private var mViewModel: HistoryApkListViewModel? = null
    private lateinit var mExposureListener: ExposureListener

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

    private val mDelayLogRunnable = Runnable {
        NewLogUtils.logGameDetailHistoryVersionView(mViewModel?.game?.name ?: "", mViewModel?.game?.id ?: "")
    }

    private val dataWatcher = object : DataWatcher() {
        override fun onDataChanged(downloadEntity: DownloadEntity) {
            mAdapter?.notifyItemByDownload(downloadEntity)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        mViewModel?.showDowngradeHint?.observeNonNull(this) {
            mBinding.tipsContainer.goneIf(!it)
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mExposureListener = ExposureListener(this, mAdapter!!)
        mListRv.addOnScrollListener(mExposureListener)
        mBaseHandler.postDelayed(mDelayLogRunnable, 3000)
    }

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

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

    override fun getItemDecoration(): RecyclerView.ItemDecoration {
        val insetDivider = InsetDrawable(
            ContextCompat.getDrawable(requireContext(), R.drawable.divider_history_apks),
            DisplayUtils.dip2px(20F),
            0,
            DisplayUtils.dip2px(20F),
            0
        )
        val itemDecoration = CustomDividerItemDecoration(requireContext(), notDecorateTheLastItem = true)
        itemDecoration.setDrawable(insetDivider)
        return itemDecoration
    }

    override fun getLayoutId() = 0
    override fun getInflatedLayout() = mBinding.root

    override fun isAutomaticLoad() = arguments?.getParcelable<GameEntity>(EntranceConsts.KEY_GAME) != null

    override fun provideListViewModel(): HistoryApkListViewModel {
        if (mViewModel == null) {
            val factory = HistoryApkListViewModel.Factory(
                HaloApp.getInstance().application,
                arguments?.getString(EntranceConsts.KEY_GAMEID) ?: "",
                arguments?.getParcelable(EntranceConsts.KEY_GAME)
            )
            mViewModel = viewModelProvider(factory)
        }

        return mViewModel!!
    }

    override fun provideListAdapter(): ListAdapter<*> {
        if (mAdapter == null) {
            mAdapter = HistoryApkListAdapter(requireContext(), mViewModel!!, mEntrance)
        }
        return mAdapter!!
    }

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

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        mBinding.root.setRootBackgroundColor(com.gh.gamecenter.common.R.color.ui_surface)
        mListRv.recycledViewPool.clear()
        mAdapter?.notifyItemRangeChanged(0, mAdapter?.itemCount ?: 0)
        if (mListRv.itemDecorationCount > 0) {
            mListRv.removeItemDecorationAt(0)
            mListRv.addItemDecoration(itemDecoration)
        }
    }
}