package com.adealink.weparty.image.preview

import android.Manifest
import android.annotation.SuppressLint
import android.os.Build
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.viewModels
import com.adealink.frame.aab.util.getCompatString
import com.adealink.frame.image.view.zoomable.IExtraListener
import com.adealink.frame.mvvm.view.viewBinding
import com.adealink.weparty.commonui.BaseFragment
import com.adealink.weparty.commonui.dialogfragment.CommonTextActionDialog
import com.adealink.weparty.commonui.toast.util.showToast
import com.adealink.weparty.commonui.widget.CommonDialog
import com.adealink.weparty.image.R
import com.adealink.weparty.image.data.TAG_IMAGE_PREVIEW
import com.adealink.weparty.image.databinding.FragmentImagePreviewBinding
import com.adealink.weparty.image.viewmodel.ImagePreviewExtensionViewModel
import com.adealink.weparty.image.viewmodel.Resource
import com.adealink.weparty.permission.PermissionUtils
import com.adealink.weparty.R as APP_R


class ImagePreviewFragment : BaseFragment(R.layout.fragment_image_preview) {
    companion object {
        private const val KEY_URL = "url"
        private const val STORAGE_PERMISSION_DIALOG = "storage_permission_dialog"
        fun newInstance(uri: String): ImagePreviewFragment {
            val fragment = ImagePreviewFragment()
            val bundle = Bundle()
            bundle.putString(KEY_URL, uri)
            fragment.arguments = bundle
            return fragment
        }
    }

    private val binding by viewBinding(FragmentImagePreviewBinding::bind)
    private val imagePreviewExtensionViewModel by viewModels<ImagePreviewExtensionViewModel>()
    private var imageUri = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        imageUri = arguments?.getString(KEY_URL) ?: ""
    }

    override fun observeViewModel() {
        super.observeViewModel()
        imagePreviewExtensionViewModel.saveResult.observe(viewLifecycleOwner) {
            when (it) {
                is Resource.Success -> {
                    showToast(R.string.image_save_success)

                }

                is Resource.Error -> {
                    Log.e(TAG_IMAGE_PREVIEW, "saveResult error, e:${it.error?.message}")
                    showToast(R.string.image_save_failed)
                }

                is Resource.Loading -> {
                    //Ntd.
                }
            }
        }
    }

    private fun showLongClickActionDialog() {
        if (!isAdded) {
            return
        }
        CommonTextActionDialog.Builder()
            .addItem(R.id.image_preview_save, APP_R.string.common_save)
            .actionListener(object : CommonTextActionDialog.CommonTextActionListener {
                override fun onActionClick(viewId: Int) {
                    when (viewId) {
                        R.id.image_preview_save -> {
                            checkStoragePermissionAndSaveImg(imageUri)
                        }
                    }
                }
            }).build().show(childFragmentManager)
    }

    override fun initViews() {
        super.initViews()
        binding.ivPhoto.extraListener = object : IExtraListener {
            override fun onLongClick() {
                //长按菜单，仅在图片加载成功后可弹出
                showLongClickActionDialog()
            }

            override fun onSwipeDown() {
                //下滑退出页面
                activity?.finish()
            }

            override fun onTap() {
                activity?.finish()
            }
        }
        binding.ivPhoto.setImagePath(imageUri)
    }

    //保存图片需要检查存储权限
    @SuppressLint("CheckResult")
    private fun checkStoragePermissionAndSaveImg(imageUri: String) {
        val act = activity ?: return
        val permission = getMediaImagePermission()
        if (PermissionUtils.hasPermissions(act, *permission)) {
            imagePreviewExtensionViewModel.saveImageToAlbum(imageUri)
        } else {
            PermissionUtils.getRxPermissions(act)
                .request(*permission).subscribe { granted ->
                    if (granted) {
                        imagePreviewExtensionViewModel.saveImageToAlbum(imageUri)
                    } else {
                        showPermissionNoGrantedDialog()
                    }
                }
        }
    }

    private fun getMediaImagePermission(): Array<String> {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            arrayOf(Manifest.permission.READ_MEDIA_IMAGES)
        } else {
            arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE)
        }
    }

    private fun showPermissionNoGrantedDialog() {
        childFragmentManager.findFragmentByTag(STORAGE_PERMISSION_DIALOG)?.let {
            childFragmentManager.beginTransaction().remove(it).commitNowAllowingStateLoss()
        }
        val permissionDialog = CommonDialog.Builder()
            .message(getCompatString(R.string.image_save_storage_permission_no_granted))
            .onPositive {
                PermissionUtils.startPermissionSettingActivity(this)
            }
            .dismissAfterClick(true)
            .setShowDefaultCancel(true)
            .build()
        permissionDialog.show(childFragmentManager, STORAGE_PERMISSION_DIALOG)
    }
}