package com.gh.gamecenter.mygame

import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.exposure.ExposureListener
import com.gh.gamecenter.common.utils.ifLogin
import com.gh.gamecenter.common.utils.toColor
import com.gh.gamecenter.common.utils.toDrawable
import com.gh.gamecenter.common.utils.viewModelProvider
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.Constants
import com.gh.gamecenter.common.databinding.FragmentListBaseBinding
import com.gh.gamecenter.entity.GameEntity
import com.gh.gamecenter.eventbus.EBDownloadStatus
import com.gh.gamecenter.eventbus.EBPackage
import com.gh.gamecenter.common.eventbus.EBReuse
import com.gh.gamecenter.login.user.UserManager
import com.lightgame.download.DataWatcher
import com.lightgame.download.DownloadEntity
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class MyReservationFragment : ListFragment<GameEntity, MyReservationViewModel>() {

    private var mAdapter: MyReservationAdapter? = null
    private lateinit var mViewModel: MyReservationViewModel
    private var mExposureListener: ExposureListener? = null
    private val mBinding by lazy { FragmentListBaseBinding.inflate(layoutInflater) }

    private val dataWatcher = object : DataWatcher() {
        override fun onDataChanged(downloadEntity: DownloadEntity) {
            val data = mAdapter?.getGameEntityByPackage(downloadEntity.packageName) ?: arrayListOf()
            for (gameAndPosition in data) {
                if (gameAndPosition.entity != null && gameAndPosition.entity.name == downloadEntity.name) {
                    val entryMap = gameAndPosition.entity.getEntryMap()
                    entryMap[downloadEntity.platform] = downloadEntity
                }
                mAdapter?.notifyItemChanged(gameAndPosition.position)
            }
        }
    }

    override fun getLayoutId() = 0

    override fun getInflatedLayout() = mBinding.root

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        mBinding.reuseNoneData.reuseNoneDataTv.setOnClickListener(this)
        mListRv.addOnScrollListener(mExposureListener!!)
        mListRv.setBackgroundColor(R.color.background_white.toColor(requireContext()))
    }

    override fun onStart() {
        super.onStart()
        if (TextUtils.isEmpty(UserManager.getInstance().userId)) {
            mBinding.reuseNoneData.reuseNoneDataTv.text = getString(R.string.login_hint)
            mBinding.reuseNoneData.reuseNoneDataTv.setTextColor(
                ContextCompat.getColor(
                    requireContext(),
                    R.color.theme_font
                )
            )
        } else {
            mBinding.reuseNoneData.reuseNoneDataTv.text = getString(R.string.game_empty)
            mBinding.reuseNoneData.reuseNoneDataTv.setTextColor(
                ContextCompat.getColor(
                    requireContext(),
                    R.color.text_title
                )
            )
        }
    }

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

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

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

    override fun provideListViewModel(): MyReservationViewModel {
        mViewModel = viewModelProvider()
        return mViewModel
    }

    override fun onClick(v: View) {
        super.onClick(v)
        when (v.id) {
            R.id.reuseNoneDataTv -> {
                val hint = getString(R.string.login_hint)
                if (hint == mBinding.reuseNoneData.reuseNoneDataTv.text.toString()) {
                    ifLogin("(我的预约)", null)
                }
            }
        }
    }

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

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMainThread(changed: EBReuse) {
        if (Constants.LOGIN_TAG == changed.type) { // 登入
            onLoadRefresh()
        }
    }

    //安装、卸载事件
    @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) {
            mAdapter?.notifyItemAndRemoveDownload(status)
        }
    }

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        mListRv.setBackgroundColor(R.color.background_white.toColor(requireContext()))
    }
}