package com.adealink.weparty.profile.edit.viewmodel

import androidx.lifecycle.MutableLiveData
import com.adealink.frame.log.Log
import com.adealink.frame.mvvm.viewmodel.BaseViewModel
import com.adealink.weparty.profile.edit.data.AddPhotoItemData
import com.adealink.weparty.profile.edit.data.BasePhotoItemData
import com.adealink.weparty.profile.edit.data.PhotoData
import com.adealink.weparty.profile.edit.data.PhotoItemData
import kotlinx.coroutines.launch

class EditProfileViewModel : BaseViewModel() {

    companion object {
        private const val TAG = "EditProfileViewModel"
        const val MAX_PHOTO_COUNT = 9
    }

    val photoList = mutableListOf<PhotoData>()

    val photoItemList = mutableListOf<BasePhotoItemData>()
    val photoItemListLD = MutableLiveData<MutableList<BasePhotoItemData>>()

    init {
        onPictureListChanged()
    }

    fun addPhoto(path: String?, uri: String?) {
        viewModelScope.launch {
            photoList.add(
                PhotoData(
                    url = null,
                    path = path,
                    uri = uri
                )
            )
            onPictureListChanged()
        }
    }

    fun removePhoto(data: PhotoData) {
        viewModelScope.launch {
            photoList.remove(data)
            onPictureListChanged()
        }
    }

    private fun onPictureListChanged() {
        photoItemList.clear()
        for ((i, data) in photoList.take(MAX_PHOTO_COUNT).withIndex()) {
            photoItemList.add(PhotoItemData(data))
        }
        //小于9张图片,可以继续添加图片
        for (i in photoList.size until MAX_PHOTO_COUNT) {
            photoItemList.add(AddPhotoItemData)
        }
        photoItemListLD.send(photoItemList)
    }

    //调整勋章位置
    val adjustPhotoPositionLD = MutableLiveData<Pair<Int, Int>>()
    fun adjustPhotoPosition(fromPosition: Int, toPosition: Int) {
        Log.d(TAG, "adjustPhotoPosition, from:$fromPosition, to:$toPosition")
        if (fromPosition < 0 || toPosition < 0) return
        val itemCount = photoItemList.size
        if (fromPosition > itemCount || toPosition > itemCount) return

        viewModelScope.launch {
            photoItemList.add(toPosition, photoItemList.removeAt(fromPosition))
            photoList.clear()
            for (itemData in photoItemList) {
                if (itemData is PhotoItemData) {
                    photoList.add(itemData.data)
                }
            }
            adjustPhotoPositionLD.send(Pair(fromPosition, toPosition))
        }
    }


}