package com.sound.prankparty.Activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Handler;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.sound.prankparty.databinding.ActivityNewRecordBinding;

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

public class NewRecordActivity extends AppCompatActivity {

    private static final int REQUEST_RECORD_AUDIO_PERMISSION = 200;

    private ActivityNewRecordBinding binding;
    private Boolean isStarted = false;
    private Handler handler = new Handler();
    private long startTime;
    private MediaRecorder mediaRecorder;
    private File outputFile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityNewRecordBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        binding.newRecordRecord.setOnClickListener(v -> {
            // 检查是否授予了RECORD_AUDIO权限
            if (ContextCompat.checkSelfPermission(NewRecordActivity.this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
                // 如果未被授予，则请求该权限
                ActivityCompat.requestPermissions(NewRecordActivity.this, new String[]{Manifest.permission.RECORD_AUDIO}, REQUEST_RECORD_AUDIO_PERMISSION);
            } else {
                // 如果获得权限，就开始录音
                toggleRecording();
            }
        });

        binding.newRecordBack.setOnClickListener(v -> onBackPressed());
    }

    private void toggleRecording() {
        if (isStarted) {
            // 停止录音
            stopRecording();
        } else {
            // 开始录音
            startRecording();
        }
        isStarted = !isStarted; // 切换录音状态
    }

    //每个一秒更新显示录音时长
    private Runnable updateTimeTask = new Runnable() {
        @Override
        public void run() {
            long currentTime = System.currentTimeMillis();
            long elapsedTime = currentTime - startTime;
            binding.newRecordTime.setText(formatTime(elapsedTime));
            handler.postDelayed(this, 1000);
        }
    };

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_RECORD_AUDIO_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 获得许可，开始录音
                toggleRecording();
            } else {
                // 权限被拒绝，通知用户
                Toast.makeText(this, "录音权限被拒绝，请在设置中启用权限", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void startRecording() {
        try {
            // 初始化MediaRecorder
            mediaRecorder = new MediaRecorder();
            mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
            mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);

            // 设置输出文件路径
            String fileName = "recording_" + System.currentTimeMillis() + ".m4a";
            outputFile = new File(getFilesDir(), fileName);
            mediaRecorder.setOutputFile(outputFile.getAbsolutePath());

            // 准备并开始录音
            mediaRecorder.prepare();
            mediaRecorder.start();

            // 更新UI
            startTime = System.currentTimeMillis();
            handler.post(updateTimeTask);
            binding.animationView.playAnimation();

        } catch (IOException e) {
            e.printStackTrace();
            // 处理异常
        }
    }

    private void stopRecording() {
        // 停止录音并释放MediaRecorder
        if (mediaRecorder != null) {
            mediaRecorder.stop();
            mediaRecorder.release();
            mediaRecorder = null;
        }

        // 更新UI
        handler.removeCallbacks(updateTimeTask);
        binding.animationView.cancelAnimation();
        binding.animationView.setFrame(0);
        binding.newRecordTime.setText("00:00:00");

        Intent intent = new Intent(NewRecordActivity.this, SaveRecordActivity.class);
        intent.putExtra("audioFilePath", outputFile.getAbsolutePath());
        startActivity(intent);
    }

    private String formatTime(long elapsedTime) {
        int seconds = (int) (elapsedTime / 1000) % 60;
        int minutes = (int) ((elapsedTime / (1000 * 60)) % 60);
        int hours = (int) ((elapsedTime / (1000 * 60 * 60)) % 24);
        return String.format("%02d:%02d:%02d", hours, minutes, seconds);
    }

    @Override
    public void onBackPressed() {
        if (isStarted) {
            // 停止录音并释放MediaRecorder
            if (mediaRecorder != null) {
                mediaRecorder.stop();
                mediaRecorder.release();
                mediaRecorder = null;
            }
            // 删除录音文件
            deleteRecordingFile();
        }
        finish();
        super.onBackPressed();
    }

    private void deleteRecordingFile() {
        if (outputFile != null && outputFile.exists()) {
            boolean deleted = outputFile.delete();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacks(updateTimeTask);
        if (isStarted) {
            // 停止录音并释放MediaRecorder
            if (mediaRecorder != null) {
                mediaRecorder.stop();
                mediaRecorder.release();
                mediaRecorder = null;
            }
            deleteRecordingFile();
        }
    }
}
