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

import android.app.Activity.RESULT_OK
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Environment
import android.os.Parcelable
import android.provider.MediaStore
import androidx.activity.result.contract.ActivityResultContract
import com.adealink.frame.util.AppUtil
import com.adealink.frame.util.FileProvider7
import kotlinx.parcelize.Parcelize
import java.io.File

data class TakePhotoRequest(val file: File)

data class TakePhotoResult(val resultCode: Int)

/**
 * 拍照 -> 系统相机
 */
class TakePhotoContract : ActivityResultContract<TakePhotoRequest, TakePhotoResult>() {

    override fun createIntent(context: Context, input: TakePhotoRequest): Intent {
        val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        val mImageCaptureUri: Uri? =
            if (Environment.MEDIA_MOUNTED == Environment.getExternalStorageState()) {
                FileProvider7.getUriForFile(AppUtil.appContext, input.file)
            } else {
                // TODO:
                Uri.parse("content://eu.janmuller.android.simplecropimage.example/")
            }
        intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageCaptureUri)
        intent.putExtra("return-data", true)
        return intent
    }

    override fun parseResult(resultCode: Int, intent: Intent?): TakePhotoResult {
        return TakePhotoResult(resultCode)
    }
}

/**
 * 录制视频 -> 自定义录屏 Activity
 */
class RecordVideoContract : ActivityResultContract<RecordVideoRequest, RecordVideoInfo>() {

    override fun createIntent(context: Context, input: RecordVideoRequest): Intent {
        return Intent(context, CameraActivity::class.java).apply {
            putExtra(CameraActivity.EXTRA_LIMITED_DURATION, input.limitedDuration)
        }
    }

    override fun parseResult(resultCode: Int, intent: Intent?): RecordVideoInfo {
        return when (resultCode) {
            RESULT_OK -> {
                val info = intent?.getParcelableExtra<RecordVideoInfo>(CameraActivity.EXTRA_VIDEO)
                info ?: RecordVideoInfo()
            }

            else -> {
                RecordVideoInfo()
            }
        }
    }
}

data class RecordVideoRequest(
    val limitedDuration: Int, // 限制录制时长，单位：秒
)

@Parcelize
data class RecordVideoInfo(
    val uri: Uri? = null,
    val path: String? = null,
    val duration: Long = 0, // 视频时长, 毫秒
) : Parcelable