package com.gh.gamecenter.video.poster.photo

import android.database.Cursor
import android.os.Bundle
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.GridLayoutManager
import com.gh.gamecenter.common.base.fragment.BaseFragment
import com.gh.gamecenter.common.utils.dip2px
import com.gh.gamecenter.R
import com.gh.gamecenter.databinding.FragmentPhotoPosterBinding
import com.zhihu.matisse.internal.entity.Album
import com.zhihu.matisse.internal.model.AlbumMediaCollection
import com.zhihu.matisse.internal.ui.widget.MediaGridInset

class PhotoPosterFragment : BaseFragment<Any>(), AlbumMediaCollection.AlbumMediaCallbacks {

    private lateinit var mViewModel: PhotoPosterViewModel

    private lateinit var mBinding: FragmentPhotoPosterBinding

    private lateinit var mAdapter: PhotoPosterAdapter

    private var mAlbumMediaCollection: AlbumMediaCollection? = null

    override fun getLayoutId(): Int {
        return R.layout.fragment_photo_poster
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = FragmentPhotoPosterBinding.bind(mCachedView)

        mViewModel = ViewModelProviders.of(this).get(PhotoPosterViewModel::class.java)

        mBinding.recyclerView.layoutManager = GridLayoutManager(requireContext(), 3)
        mBinding.recyclerView.addItemDecoration(MediaGridInset(3, 2F.dip2px(), false))
        mAdapter = PhotoPosterAdapter()
        mBinding.recyclerView.adapter = mAdapter
    }

    override fun onAlbumMediaReset() {
        mAdapter.swapCursor(null)
    }

    override fun onAlbumMediaLoad(cursor: Cursor?) {
        mAdapter.swapCursor(cursor)
    }

    fun loadPhotos(album: Album) {
        if (isAdded) {
            mAlbumMediaCollection?.onDestroy()

            mAlbumMediaCollection = AlbumMediaCollection()
            mAlbumMediaCollection?.onCreate(requireActivity(), this)
            mAlbumMediaCollection?.load(album)
        }
    }

    fun getSelectImagePath(): String? {
        if (isAdded) {
            return mAdapter.getSelectImagePath()
        }
        return null
    }

    companion object {

        fun newInstance(): PhotoPosterFragment {
            return PhotoPosterFragment()
        }
    }
}