package com.gh.gamecenter.gamedetail.cloudarchive

import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.gh.gamecenter.R
import com.gh.gamecenter.common.baselist.LazyListFragment
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.utils.observeNonNull
import com.gh.gamecenter.common.utils.toDrawable
import com.gh.gamecenter.common.utils.toResString
import com.gh.gamecenter.common.utils.viewModelProvider
import com.gh.gamecenter.common.view.CustomDividerItemDecoration
import com.gh.gamecenter.entity.ArchiveEntity
import com.gh.gamecenter.entity.GameEntity

class CloudArchiveListFragment : LazyListFragment<ArchiveEntity, CloudArchiveListViewModel>() {

    private var mAdapter: CloudArchiveListAdapter? = null

    override fun provideListAdapter() = mAdapter
        ?: CloudArchiveListAdapter(
            requireContext(),
            arguments?.getParcelable<GameEntity>(EntranceConsts.KEY_GAME)?.getUniquePackageName() ?: "",
            this,
            mListViewModel ?: provideListViewModel()
        ).apply { mAdapter = this }

    override fun provideListViewModel() =
        viewModelProvider<CloudArchiveListViewModel>(
            CloudArchiveListViewModel.Factory(
                arguments?.getParcelable<GameEntity>(EntranceConsts.KEY_GAME)?.id ?: "",
                arguments?.getString(EntranceConsts.KEY_SEARCHKEY) ?: ""
            )
        )

    override fun getItemDecoration(): RecyclerView.ItemDecoration {
        return CustomDividerItemDecoration(
            requireContext(),
            notDecorateTheLastItem = true
        ).apply {
            setDrawable(R.drawable.divider_item_line_space_16.toDrawable(requireContext())!!)
            mItemDecoration = this
        }
    }

    override fun onFragmentFirstVisible() {
        super.onFragmentFirstVisible()
        mListViewModel?.refresh?.observeNonNull(this) { onRefresh() }
    }

    override fun initRealView() {
        super.initRealView()
        mReuseNoData?.findViewById<TextView>(R.id.reuseNoneDataTv)?.text =
            R.string.game_detail_cloud_archive_list_empty.toResString()
        mReuseNoData?.findViewById<TextView>(R.id.reuseNoneDataDescTv)?.text =
            R.string.game_detail_cloud_archive_list_empty_desc.toResString()
    }

    override fun onLoadEmpty() {
        mReuseNoData?.findViewById<TextView>(R.id.reuseNoneDataDescTv)?.visibility = View.VISIBLE
        super.onLoadEmpty()
    }

    fun updateSortType(sortType: CloudArchiveListViewModel.SortType) {
        mListViewModel?.update(sortType)
    }

    fun updateSearchKeyWord(keyWord: String) {
        mListViewModel?.update(keyWord = keyWord)
    }
}