package com.adealink.weparty.commonui.mediapicker.imageselect.selectpreview

import android.app.Activity
import android.content.Context
import android.content.Intent
import androidx.activity.result.contract.ActivityResultContract

data class SelectPreviewRequest(
    val source: String,
    val path: String?,
    val uri: String?,
    val previewType: SelectPreviewType = SelectPreviewType.IMAGE,
    val showConfirm: Boolean = true,
)

data class SelectPreviewResult(
    val source: String,
    val resultCode: Int,
    val path: String?,
    val uri: String?,
    val previewType: SelectPreviewType?,
)

// 预览的媒体类型
enum class SelectPreviewType {
    IMAGE, VIDEO,
}

class SelectPreviewContract : ActivityResultContract<SelectPreviewRequest, SelectPreviewResult>() {

    override fun createIntent(context: Context, input: SelectPreviewRequest): Intent {
        val intent = Intent(context, SelectPreviewActivity::class.java)
        intent.putExtra(SelectPreviewActivity.KEY_SOURCE, input.source)
        intent.putExtra(SelectPreviewActivity.KEY_PATH, input.path)
        intent.putExtra(SelectPreviewActivity.KEY_URI, input.uri)
        intent.putExtra(SelectPreviewActivity.KEY_SHOW_CONFIRM, input.showConfirm)
        intent.putExtra(SelectPreviewActivity.KEY_PREVIEW_TYPE, input.previewType.name)
        return intent
    }

    override fun parseResult(resultCode: Int, intent: Intent?): SelectPreviewResult {
        val source: String = intent?.getStringExtra(SelectPreviewActivity.KEY_SOURCE) ?: ""
        val path: String? = intent?.getStringExtra(SelectPreviewActivity.KEY_PATH)
        val uri: String? = intent?.getStringExtra(SelectPreviewActivity.KEY_URI)
        val previewTypeStr: String? = intent?.getStringExtra(SelectPreviewActivity.KEY_PREVIEW_TYPE)
        val previewType =
            if (previewTypeStr == SelectPreviewType.VIDEO.name) SelectPreviewType.VIDEO else SelectPreviewType.IMAGE
        return SelectPreviewResult(
            source,
            resultCode,
            if (resultCode == Activity.RESULT_OK) path else null,
            if (resultCode == Activity.RESULT_OK) uri else null,
            if (resultCode == Activity.RESULT_OK) previewType else null,
        )
    }
}