package com.remax.visualnovel.utils

import android.app.Activity
import android.os.Environment
import com.buihha.audiorecorder.Mp3Recorder
import com.buihha.audiorecorder.Mp3Recorder.OnRecordListener
import timber.log.Timber
import java.io.File

/**
 * Created by HJW on 2025/8/16
 */
class RecordHelper {

    private var recorder: Mp3Recorder? = null
    private var filename: String = "null"

    fun isRecording(): Boolean {
        return recorder != null && recorder!!.isRecording()
    }

    @Synchronized
    fun startRecording(activity: Activity, onStart: () -> Unit, onStop: () -> Unit) {
        try {
            recorder = Mp3Recorder()
            recorder!!.setOnRecordListener(object : OnRecordListener {
                override fun onStart() {
                    //开始录音
                    onStart.invoke()
                }

                override fun onStop() {
                    //停止录音
                    onStop.invoke()
                }

                override fun onError() {
                    Timber.i("startRecording onError")
                    //录音错误，主要针对OPPO手机在调用startRecord方法时弹窗安全权限提示，此时如果拒绝，则会执行该回调
                    onStop.invoke()
                }

                override fun onRecording(i: Int, v: Double) {
                    //Timber.d("采样:" + i + "Hz   音量:" + v + "分贝");
                }
            })
            if (!recorder!!.isRecording()) {
                val filePath = activity.getExternalFilesDir(Environment.DIRECTORY_MUSIC)
                val file = File(
                    filePath,
                      "record_${System.currentTimeMillis()}.mp3"
                )
                filename = file.path
                recorder!!.startRecording(filePath?.path, file.getName())
            }
        } catch (e: Exception) {
            Timber.i("startRecording catch :${e.localizedMessage}")
            e.printStackTrace()
            onStop.invoke()
        }
    }

    @Synchronized
    fun stopRecording() {
        try {
            if (recorder != null && recorder!!.isRecording()) {
                recorder!!.stopRecording()
                recorder = null
            }
        } catch (e: Exception) {
            e.printStackTrace()
            Timber.i("startRecording stopRecording :${e.localizedMessage}")

            recorder = null

            val file = File(filename)
            if (file.exists()) {
                file.delete()
            }
        }
    }

    fun getFilename(): String {
        return filename
    }

    fun setFilename(filename: String) {
        this.filename = filename
    }

}