package com.dronex.rec.recording

import android.content.ContentValues
import android.content.Context
import android.os.Build
import android.provider.MediaStore
import androidx.camera.video.MediaStoreOutputOptions
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

object RecordingOutputFactory {
    private const val RELATIVE_PATH = "Movies/飞行极控录像工作台"
    private const val MIME_TYPE = "video/mp4"

    fun buildMediaStoreOutputOptions(
            context: Context,
            displayName: String?,
    ): MediaStoreOutputOptions {
        val fileName = resolveFileName(displayName)
        val contentValues =
                ContentValues().apply {
                    put(MediaStore.MediaColumns.DISPLAY_NAME, fileName)
                    put(MediaStore.MediaColumns.MIME_TYPE, MIME_TYPE)
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                        put(MediaStore.Video.Media.RELATIVE_PATH, RELATIVE_PATH)
                    }
                }

        return MediaStoreOutputOptions.Builder(
                        context.contentResolver,
                        MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
                )
                .setContentValues(contentValues)
                .build()
    }

    fun resolveFileName(displayName: String?): String {
        val trimmed = displayName?.trim().orEmpty()
        if (trimmed.isNotEmpty()) {
            return if (trimmed.lowercase(Locale.US).endsWith(".mp4")) {
                trimmed
            } else {
                "$trimmed.mp4"
            }
        }
        val timestamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(Date())
        return "REC_$timestamp.mp4"
    }
}
