package com.gh.gamecenter.video.game

import android.os.Bundle
import android.view.View
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.constant.Config
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.utils.dip2px
import com.gh.gamecenter.common.view.GridSpacingItemDecoration
import com.gh.gamecenter.common.baselist.ListFragment
import com.gh.gamecenter.common.baselist.NormalListViewModel
import com.gh.gamecenter.entity.MyVideoEntity
import com.gh.gamecenter.retrofit.RetrofitManager
import com.halo.assistant.HaloApp
import io.reactivex.Observable

class GameVideoFragment : ListFragment<MyVideoEntity, NormalListViewModel<MyVideoEntity>>() {
    private var mAdapter: GameVideoAdapter? = null

    override fun provideListAdapter(): GameVideoAdapter {
        if (mAdapter == null) {
            mAdapter = GameVideoAdapter(
                requireContext(),
                mListViewModel,
                mEntrance,
                arguments?.getString(EntranceConsts.KEY_SORT),
                arguments?.getString(EntranceConsts.KEY_GAMEID) ?: ""
            )
        }
        return mAdapter!!
    }

    override fun getItemDecoration(): RecyclerView.ItemDecoration {
        return GridSpacingItemDecoration(2, 8F.dip2px(), false, 8F.dip2px())
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mListRv.setPadding(8F.dip2px(), 0, 8F.dip2px(), 0)
        val gridLayoutManager = GridLayoutManager(requireContext(), 2)
        gridLayoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
            override fun getSpanSize(position: Int): Int {
                return if (position == mAdapter!!.itemCount - 1) {
                    2
                } else {
                    1
                }
            }
        }
        mListRv.layoutManager = gridLayoutManager
    }

    override fun provideListViewModel(): NormalListViewModel<MyVideoEntity> {
        val factory = NormalListViewModel.Factory(HaloApp.getInstance().application, this)
        return ViewModelProviders.of(this, factory)
            .get(NormalListViewModel::class.java) as NormalListViewModel<MyVideoEntity>
    }

    override fun provideDataObservable(page: Int): Observable<MutableList<MyVideoEntity>> {
        val api = RetrofitManager.getInstance().api
        val gameId = arguments?.getString(EntranceConsts.KEY_GAMEID)
        val sort = arguments?.getString(EntranceConsts.KEY_SORT)
        return api.getGameVideo(gameId, sort, page, Config.VIDEO_PAGE_SIZE)
    }

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        mAdapter?.notifyItemRangeChanged(0, mAdapter?.itemCount ?: 0)
    }
}