package com.meeting.demo.utils;

import android.os.Environment;

import com.huawei.hwmlogger.HCLog;
import com.huawei.hwmsdk.model.result.AudioFrameData;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class VoiceRecordUtils {
    private static final String TAG = VoiceRecordUtils.class.getSimpleName();
    private static boolean isVoiceRecordChecked = false;
    private static FileOutputStream fos;

    public static boolean isVoiceRecordChecked() {
        return isVoiceRecordChecked;
    }

    public static void setVoiceRecordChecked(boolean isVoiceRecordChecked) {
        VoiceRecordUtils.isVoiceRecordChecked = isVoiceRecordChecked;
        if (isVoiceRecordChecked) {
            startRecording();
        } else {
            stopRecording();
        }
    }

    public synchronized static void startRecording() {
        HCLog.i(TAG, "startRecording");
        File musicDir = DemoUtil.getApplication().getExternalFilesDir(Environment.DIRECTORY_MUSIC);
        File audioFile = new File(musicDir, generateRandomAudioFileName());

        try {
            File parentDir = audioFile.getParentFile();
            if (parentDir != null && !parentDir.exists()) {
                parentDir.mkdirs();
            }

            fos = new FileOutputStream(audioFile, true);
        } catch (Exception e) {
            HCLog.e(TAG, "Failed to start recording: " + e.toString());
        }
    }

    private static String generateRandomAudioFileName() {
        return "recording_" + System.currentTimeMillis() + ".pcm";
    }

    public synchronized static void onAudioFrameNotify(AudioFrameData pFrame) {
        try {
            if (fos != null) {
                fos.write(pFrame.getPBuffer());
            }
        } catch (IOException e) {
            HCLog.e(TAG, "Failed to write PCM data: " + e.toString());
        }
    }

    public synchronized static void stopRecording() {
        HCLog.i(TAG, "stopRecording.");
        try {
            if (fos != null) {
                fos.close();
                fos = null;
            }
        } catch (IOException e) {
            HCLog.e(TAG, "Failed to close FileOutputStream: " + e.toString());
        }
    }
}
