package com.gh.gamecenter.collection

import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.utils.dip2px
import com.gh.gamecenter.common.utils.viewModelProvider
import com.gh.gamecenter.common.view.GridSpacingItemDecoration
import com.gh.gamecenter.common.baselist.ListFragment
import com.gh.gamecenter.entity.MyVideoEntity
import com.gh.gamecenter.history.IBatchDelete
import com.gh.gamecenter.history.ManageOption

class VideoFragment : ListFragment<MyVideoEntity, VideoViewModel>(), IBatchDelete {
    private var mAdapter: VideoAdapter? = null
    private var mViewModel: VideoViewModel? = null
    private lateinit var mVideoStyle: String
    private var mIsInsertBbsVideo: Boolean = false

    override fun provideListAdapter(): VideoAdapter {
        if (mAdapter == null) {
            mAdapter = VideoAdapter(requireContext(), mViewModel!!, mVideoStyle, mIsInsertBbsVideo, mEntrance)
        }
        return mAdapter!!
    }

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

    override fun onCreate(savedInstanceState: Bundle?) {
        mVideoStyle = requireArguments().getString("videoStyle") ?: ""
        mIsInsertBbsVideo = requireArguments().getBoolean(EntranceConsts.KEY_INSERT_BBS_VIDEO)
        super.onCreate(savedInstanceState)
        mListRv.setPadding(8f.dip2px(), 0, 8f.dip2px(), 0)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val gridLayoutManager = GridLayoutManager(context, 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(): VideoViewModel {
        if (mViewModel == null) {
            mViewModel = viewModelProvider()
        }
        mViewModel?.type = mVideoStyle
        return mViewModel!!
    }

    override fun changeOption(option: ManageOption) {
        mAdapter?.changeOption(option)
    }

    enum class VideoStyle(val value: String) {
        COLLECT("collect"),
        MINE("mine"),
        BROWSING_HISTORY("browsing_history");

        override fun toString() = value
    }

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        if ((mListRv?.itemDecorationCount ?: 0) > 0) {
            mListRv?.removeItemDecorationAt(0)
            mListRv?.addItemDecoration(itemDecoration)
        }
    }

}