package com.adealink.weparty.commonui.widget

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.isVisible
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import com.adealink.weparty.commonui.ext.gone
import com.adealink.weparty.commonui.ext.show
import com.adealink.weparty.databinding.WidgetUploadProgressBinding
import com.adealink.weparty.module.image.data.MediaUpload

class UploadProgressView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0,
) : ConstraintLayout(context, attrs, defStyleAttr) {

    private val binding = WidgetUploadProgressBinding.inflate(LayoutInflater.from(context), this)

    private val onStartObserver = object : Observer<Unit> {
        override fun onChanged(value: Unit) {
            onStart()
        }
    }

    private val onEndObserver = object : Observer<Unit> {
        override fun onChanged(value: Unit) {
            onEnd()
        }
    }

    private val onProgressObserver = object : Observer<Pair<Long, Long>> {
        override fun onChanged(value: Pair<Long, Long>) {
            onProgress(value.first, value.second)
        }
    }

    private var uploadData: MediaUpload? = null

    fun observeProgress(owner: LifecycleOwner, upload: MediaUpload) {
        unObserve(owner)
        this.uploadData = upload
        upload.startLD.observeWithoutCache(owner, onStartObserver)
        upload.endLD.observeWithoutCache(owner, onEndObserver)
        upload.progressLD.observeWithoutCache(owner, onProgressObserver)
    }

    fun unObserve(owner: LifecycleOwner) {
        val upload = uploadData ?: return
        upload.startLD.removeObservers(owner)
        upload.endLD.removeObservers(owner)
        upload.progressLD.removeObservers(owner)
    }

    private fun onStart() {
        show()
    }

    private fun onProgress(current: Long, total: Long) {
        if (!isVisible) {
            return
        }
        binding.vProgress.max = total.toInt()
        binding.vProgress.progress = current.toInt()
    }

    private fun onEnd() {
        gone()
    }

}