package com.adealink.weparty.imageselect.selectpreview

import android.content.Intent
import android.view.View
import com.adealink.frame.effect.data.INFINITE_LOOP
import com.adealink.frame.effect.video.controller.VideoScalingMode
import com.adealink.frame.mvvm.view.viewBinding
import com.adealink.weparty.commonui.BaseActivity
import com.adealink.weparty.commonui.ext.show
import com.adealink.weparty.databinding.ActivitySelectPreviewBinding

/**
 * 支持预览类型：图片、视频
 */
class SelectPreviewActivity : BaseActivity() {
    private val binding by viewBinding(ActivitySelectPreviewBinding::inflate)
    private var uri = ""
    private var source = ""
    private var path = ""
    private var showConfirm = true
    private var previewType = SelectPreviewType.IMAGE.name

    override fun onBeforeCreate() {
        super.onBeforeCreate()
        uri = intent?.getStringExtra(KEY_URI) ?: ""
        source = intent?.getStringExtra(KEY_SOURCE) ?: ""
        path = intent?.getStringExtra(KEY_PATH) ?: ""
        showConfirm = intent?.getBooleanExtra(KEY_SHOW_CONFIRM, true) ?: true
        previewType = intent?.getStringExtra(KEY_PREVIEW_TYPE) ?: SelectPreviewType.IMAGE.name
    }

    override fun initViews() {
        setContentView(binding.root)
        if (SelectPreviewType.VIDEO.name == previewType) { // 视频预览
            binding.ivPhoto.visibility = View.GONE
            binding.videoView.visibility = View.VISIBLE
            playVideo(uri)
        } else { // 图片预览
            binding.videoView.visibility = View.GONE
            binding.ivPhoto.visibility = View.VISIBLE
            binding.ivPhoto.setImagePath(path.ifEmpty { uri })
        }
        if (showConfirm) {
            binding.clBottom.show()
            binding.btnConfirm.setOnClickListener {
                val intent = Intent()
                intent.putExtra(KEY_SOURCE, source)
                intent.putExtra(KEY_PATH, path)
                intent.putExtra(KEY_URI, uri)
                intent.putExtra(KEY_PREVIEW_TYPE, previewType)
                setResult(RESULT_OK, intent)
                finish()
            }
            binding.btnCancel.setOnClickListener {
                onCancelAction()
            }
        }
        binding.back.setOnClickListener {
            onCancelAction()
        }
    }

    private fun onCancelAction() {
        setResult(RESULT_CANCELED)
        finish()
    }

    private fun playVideo(url: String) {
        binding.videoView.setVideoScalingMode(VideoScalingMode.ScaleToFitWithCropping)
        binding.videoView.setAutoPlay(true)
        binding.videoView.setLoopCount(INFINITE_LOOP)
        binding.videoView.setUri(url)
    }


    companion object {
        const val TAG = "SelectPreviewActivity"
        const val KEY_SOURCE = "source"
        const val KEY_PATH = "select_path"
        const val KEY_URI = "select_uri"
        const val KEY_SHOW_CONFIRM = "key_show_confirm"
        const val KEY_PREVIEW_TYPE = "key_preview_type"
    }
}