package com.gh.gamecenter.gamecollection.choose

import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.utils.toColor
import com.gh.gamecenter.common.utils.viewModelProvider
import com.gh.gamecenter.R
import com.gh.gamecenter.common.baselist.ListAdapter
import com.gh.gamecenter.common.baselist.ListFragment
import com.gh.gamecenter.common.utils.setRootBackgroundColor
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.mygame.PlayedGameViewModel
import com.gh.gamecenter.qa.editor.GameAdapter

class AddUserPlayedGameFragment : ListFragment<GameEntity, PlayedGameViewModel>() {

    private var mAdapter: GameAdapter? = null
    private lateinit var mViewModel: PlayedGameViewModel
    private lateinit var mChooseGamesViewModel: ChooseGamesViewModel

    override fun getLayoutId(): Int = R.layout.fragment_add_user_played_game

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mChooseGamesViewModel = viewModelProvider(ChooseGamesViewModel.Factory())
        mChooseGamesViewModel.deleteOrAddGameLiveData.observe(this) {
            mAdapter?.entityList?.forEachIndexed { index, gameEntity ->
                if (gameEntity.id == it.id) {
                    mAdapter?.notifyItemChanged(index)
                }
            }
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mCachedView.setBackgroundColor(R.color.background_white.toColor(requireContext()))
    }

    override fun provideListAdapter(): ListAdapter<GameEntity> {
        return mAdapter ?: AddSearchAndPlayedGameAdapter(requireContext(), mChooseGamesViewModel).apply {
            mAdapter = this
        }
    }

    override fun getItemDecoration(): RecyclerView.ItemDecoration? {
        return null
    }

    override fun provideListViewModel(): PlayedGameViewModel {
        val userId = arguments?.getString(EntranceConsts.KEY_USER_ID)
            ?: UserManager.getInstance().userId
        mViewModel = viewModelProvider(AddUserPlayedGameViewModel.Factory(userId, true))
        return mViewModel
    }

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        mCachedView?.setRootBackgroundColor(R.color.background_white)
        mCachedView?.findViewById<View>(R.id.divider)?.setBackgroundColor(R.color.divider.toColor(requireContext()))
        mAdapter?.let { it.notifyItemRangeChanged(0, it.itemCount) }
    }
}