package com.adealink.weparty.joinus.step2.comp

import androidx.lifecycle.LifecycleOwner
import com.adealink.frame.mvvm.viewmodel.viewModels
import com.adealink.frame.util.onClick
import com.adealink.weparty.commonui.BaseViewComponent
import com.adealink.weparty.commonui.commonSelectedDrawable
import com.adealink.weparty.commonui.ext.dpf
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.joinus.databinding.LayoutJoinUsStep2EditAvatarBinding
import com.adealink.weparty.joinus.step2.dialog.ExampleAvatarDialog
import com.adealink.weparty.joinus.step2.viewmodel.Step2ViewModel
import com.adealink.weparty.joinus.viewmodel.JoinUsViewModelFactory
import com.adealink.weparty.module.image.data.PhotoData

class EditAvatarComp(
    lifecycleOwner: LifecycleOwner,
    private val binding: LayoutJoinUsStep2EditAvatarBinding
) : BaseViewComponent(lifecycleOwner) {

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

    private val editViewModel by viewModels<Step2ViewModel> { JoinUsViewModelFactory() }
    private lateinit var takeFromAlbumComp: TakeFromAlbumComp

    override fun initViews() {
        binding.vAvatar.root.onClick {
            modifyAvatar()
        }
        binding.btnExample.background = commonSelectedDrawable(200.dpf(), 1.dpf())
        binding.btnExample.onClick {
            ExampleAvatarDialog().show(fragmentManager, "ExampleAvatarDialog")
        }
    }

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

    override 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)
        }
    }

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

}