package com.adealink.weparty.commonui.mediapicker.videoselect

import android.app.Activity
import android.content.ContentResolver
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.MediaStore
import androidx.activity.result.contract.ActivityResultContract
import com.adealink.frame.util.AppUtil
import com.adealink.weparty.commonui.mediapicker.imageselect.model.MEDIA_TYPE_VIDEO
import com.facebook.common.util.UriUtil

data class VideoSelectRequest(
    val maxNum: Int = 1,
    val source: String = "",
)

data class VideoSelectResult(
    val source: String,
    val resultCode: Int,
    val path: String?,
    val uri: String?,
)

class VideoSelectContract : ActivityResultContract<VideoSelectRequest, VideoSelectResult>() {

    private var source: String = ""

    override fun createIntent(context: Context, input: VideoSelectRequest): Intent {
        val intent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            Intent(MediaStore.ACTION_PICK_IMAGES).apply {
                source = input.source
                type = MEDIA_TYPE_VIDEO
            }
        } else {
            Intent(context, VideoSelectActivity::class.java).apply {
                putExtra(VideoSelectActivity.KEY_SOURCE, input.source)
            }
        }
        return intent
    }

    override fun parseResult(resultCode: Int, intent: Intent?): VideoSelectResult {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            val uri: Uri? = intent?.data
            var contentResolver: ContentResolver? = null
            if (resultCode == Activity.RESULT_OK) {
                contentResolver = AppUtil.appContext.contentResolver
            }
            return VideoSelectResult(
                source,
                resultCode,
                if (resultCode == Activity.RESULT_OK && uri != null) UriUtil.getRealPathFromUri(
                    contentResolver!!,
                    uri
                ) else null,
                if (resultCode == Activity.RESULT_OK) uri?.toString() else null
            )
        } else {
            val source: String =
                intent?.getStringExtra(VideoSelectActivity.KEY_SOURCE) ?: ""
            val path: String? =
                intent?.getStringExtra(VideoSelectActivity.KEY_VIDEO_PATH)
            val uri: String? = intent?.getStringExtra(VideoSelectActivity.KEY_VIDEO_URI)
            return VideoSelectResult(
                source,
                resultCode,
                if (resultCode == Activity.RESULT_OK) path else null,
                if (resultCode == Activity.RESULT_OK) uri else null
            )
        }
    }
}