package com.sound.prankparty.SecondFragment;

import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.sound.prankparty.Main.MainActivity;
import com.sound.prankparty.R;
import com.sound.prankparty.Room.AppDatabase;
import com.sound.prankparty.Room.SaveSounds;
import com.sound.prankparty.Room.SaveSoundsDao;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class SaveRecordActivity extends AppCompatActivity {

    private String audioFilePath;
    private String inputText;
    private MediaPlayer mediaPlayer;
    private TextView durationTextView;
    private String datePart;
    private String timePart;
    private ImageView playButton;
    private EditText editText;
    private Button saveButton;
    private boolean isPlaying = false;
    private AppDatabase appDatabase;
    private SaveSoundsDao saveSoundsDao;
    private int duration;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_save_record);

        // 获取传递过来的录音文件路径
        audioFilePath = getIntent().getStringExtra("audioFilePath");
        if (audioFilePath == null) {
            Toast.makeText(this, "音频文件路径无效", Toast.LENGTH_SHORT).show();
            return;
        }
        Log.d("SaveRecordActivity", audioFilePath);

        playButton = findViewById(R.id.save_record_play);
        durationTextView = findViewById(R.id.save_record_time);
        editText = findViewById(R.id.save_record_name);
        saveButton = findViewById(R.id.save_record_save);

        // 初始化数据库和 DAO
        appDatabase = AppDatabase.getDatabase(this); // 获取数据库实例
        saveSoundsDao = appDatabase.saveSoundsDao();

        // 设置焦点变化监听器
        editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                editText.setCursorVisible(hasFocus);
            }
        });

        // 处理全局点击事件
        findViewById(R.id.main).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (v instanceof ViewGroup) {
                    clearFocusFromAllChildren((ViewGroup) v);
                } else {
                    clearFocus();
                }
                // 获取输入文本
                inputText = editText.getText().toString();
                Log.d("lux231", "13" + inputText);
            }
        });

        // 显示音频文件的时长
        displayAudioDuration();

        playButton.setOnClickListener(v -> playOrPauseAudio());

        saveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                inputText = editText.getText().toString();
                if (inputText == null || inputText.trim().isEmpty()) {
                    Toast.makeText(getApplicationContext(), "名称不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }

                formatDateTime();

                new Thread(new Runnable() {
                    @Override
                    public void run() {

                        saveSoundsDao.insertSound(new SaveSounds(inputText, audioFilePath, datePart, timePart, formatTime(duration)));

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {

                                //FLAG_ACTIVITY_CLEAR_TOP标志来清除栈中的Activity，传递Intent.FLAG_ACTIVITY_SINGLE_TOP
                                Intent intent = new Intent(SaveRecordActivity.this, MainActivity.class);
                                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                                startActivity(intent);
                                finish();
                            }
                        });
                    }
                }).start();
            }
        });
    }

    private void clearFocusFromAllChildren(ViewGroup parent) {
        for (int i = 0; i < parent.getChildCount(); i++) {
            View child = parent.getChildAt(i);
            if (child instanceof ViewGroup) {
                clearFocusFromAllChildren((ViewGroup) child);
            } else {
                child.clearFocus();
            }
        }
    }

    private void clearFocus() {
        editText.clearFocus();
    }

    private void displayAudioDuration() {
        if (audioFilePath != null) {
            mediaPlayer = new MediaPlayer();
            try {
                mediaPlayer.setDataSource(audioFilePath);
                mediaPlayer.prepare();

                // 获取音频文件的时长
                duration = mediaPlayer.getDuration();
                durationTextView.setText(formatTime(duration));

            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(this, "无法加载音频", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(this, "音频文件路径无效", Toast.LENGTH_SHORT).show();
        }
    }

    private void playOrPauseAudio() {
        if (isPlaying) {
            mediaPlayer.pause();
            playButton.setImageResource(R.drawable.playback);  // 更新按钮为播放图标
            isPlaying = false;
        } else {
            if (mediaPlayer == null) {
                mediaPlayer = new MediaPlayer();
                try {
                    mediaPlayer.setDataSource(audioFilePath);
                    mediaPlayer.prepare();
                } catch (IOException e) {
                    e.printStackTrace();
                    Toast.makeText(this, "无法播放音频", Toast.LENGTH_SHORT).show();
                    return;
                }
            }
            mediaPlayer.start();
            playButton.setImageResource(R.drawable.pause);  // 更新按钮为暂停图标
            isPlaying = true;

            mediaPlayer.setOnCompletionListener(mp -> {
                Toast.makeText(this, "播放完成", Toast.LENGTH_SHORT).show();
                playButton.setImageResource(R.drawable.playback);  // 恢复播放图标
                isPlaying = false;
            });
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null) {
            if (isPlaying) {
                mediaPlayer.stop();
            }
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }

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

    private void formatDateTime() {
        Date currentDate = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        datePart = dateFormat.format(currentDate);
        SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
        timePart = timeFormat.format(currentDate);
    }
}
