package com.gh.gamecenter.feature.selector

import android.database.Cursor
import com.zhihu.matisse.internal.entity.Item
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow

class LocalMediaRepository {

    private val _itemListFlow = MutableStateFlow<List<Item>>(arrayListOf())
    val itemListFlow: StateFlow<List<Item>> = _itemListFlow

    private val _selectedItemListFlow = MutableStateFlow<List<Item>>(arrayListOf())
    val selectedItemListFlow: StateFlow<List<Item>> = _selectedItemListFlow

    private var albumCursor: Cursor? = null

    fun updateAlbumCursor(cursor: Cursor?) {
        albumCursor = cursor
    }

    suspend fun refreshAlbumMediaData() {
        val itemList = ArrayList<Item>()
        albumCursor?.moveToFirst()
        albumCursor?.let {
            var position = 0
            while (it.moveToPosition(position)) {
                itemList.add(Item.valueOf(it).also {
                    it.positionInAlbum = position++
                })
            }
        }
        _itemListFlow.emit(itemList)
    }

    fun addSelection(item: Item) {
        // 不允许重复选中
        if (_selectedItemListFlow.value.any { it.contentUri == item.contentUri }) {
            return
        }

        val newList = ArrayList(_selectedItemListFlow.value).apply { add(item) }
        _selectedItemListFlow.tryEmit(newList)
    }

    fun removeSelection(item: Item) {
        val newList = ArrayList(_selectedItemListFlow.value).apply { remove(item) }
        _selectedItemListFlow.tryEmit(newList)
    }

    fun setSelection(item: Item) {
        _selectedItemListFlow.tryEmit(arrayListOf(item))
    }

    fun closeCursor() {
        albumCursor?.close()
    }

}