package com.adealink.weparty.profile.edit.comp

import androidx.lifecycle.LifecycleOwner
import com.adealink.frame.mvvm.view.ViewComponent
import com.adealink.frame.mvvm.viewmodel.activityViewModels
import com.adealink.frame.util.onClick
import com.adealink.weparty.commonui.ext.gone
import com.adealink.weparty.commonui.ext.show
import com.adealink.weparty.commonui.mediapicker.imageselect.clip.avatarClipParam
import com.adealink.weparty.commonui.mediapicker.imageselect.comp.TakeFromAlbumComp
import com.adealink.weparty.module.image.data.PhotoData
import com.adealink.weparty.profile.databinding.LayoutEditProfileAvatarBinding
import com.adealink.weparty.profile.edit.viewmodel.EditProfileViewModel
import com.adealink.weparty.profile.viewmodel.ProfileViewModelFactory

class EditAvatarComp(
    lifecycleOwner: LifecycleOwner,
    private val binding: LayoutEditProfileAvatarBinding
) : ViewComponent(lifecycleOwner) {

    companion object {
        private const val TAG = "EditAvatarComp"
    }

    private val editViewModel by activityViewModels<EditProfileViewModel> { ProfileViewModelFactory() }
    private lateinit var takeFromAlbumComp: TakeFromAlbumComp
    override fun onCreate() {
        super.onCreate()
        initView()
        initViewComponent()
        observeViewModel()
    }

    private fun initView() {
        binding.vAvatar.root.onClick {
            modifyAvatar()
        }
    }

    private fun initViewComponent() {
        TakeFromAlbumComp(
            viewLifecycleOwner,
            clipParamData = avatarClipParam,
            onSelect = { path, uri ->
                editViewModel.setAvatar(null, path, uri)
            },
            source = "EditAvatarComp"
        ).also {
            takeFromAlbumComp = it
        }.attach()
    }

    private fun observeViewModel() {
        editViewModel.editUserInfoLD.observe(viewLifecycleOwner) {
            updateAvatar(it.avatar)
        }
    }

    private fun updateAvatar(photoData: PhotoData?) {
        if (photoData == null || photoData.isNull()) {
            binding.vAvatar.vModifyAvatar.show()
            binding.vAvatar.vRemoveAvatar.gone()
            return
        }
        binding.vAvatar.vModifyAvatar.gone()
        binding.vAvatar.vRemoveAvatar.show()
        if (photoData.isRemote()) {
            binding.vAvatar.ivAvatar.setImageUrl(photoData.url)
        } else {
            binding.vAvatar.ivAvatar.setImageURI(photoData.uri)
        }
        binding.vAvatar.vUploadProgress.observeProgress(viewLifecycleOwner, photoData.mediaUpload)
    }

    private fun modifyAvatar() {
        takeFromAlbumComp.takeFromAlbum()
    }

}