package com.sound.prankparty.FirstFragment;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.sound.prankparty.Application.MainApplication;
import com.sound.prankparty.JSON.SoundItem;
import com.sound.prankparty.R;
import com.sound.prankparty.Room.AppDatabase;
import com.sound.prankparty.Room.FavoriteSounds;
import com.sound.prankparty.Room.FavoriteSoundsDao;

import java.io.IOException;

public class PlaySoundActivity extends AppCompatActivity {

    private MediaPlayer mediaPlayer;
    private ImageView playBack;
    private SoundItem soundItemList;
    private ImageView imageView;
    private SeekBar seekBar;
    private AudioManager audioManager;
    private boolean isPlaying = false; // 默认未播放
    private ImageView loop;
    private boolean isLooping = false; // 默认不循环
    private TextView textView;
    private AppDatabase appDatabase;
    private FavoriteSoundsDao favoriteSoundsDao;
    private ImageView favorite;
    private boolean isFavorite = false; //默认不收藏

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

        // 获取音频管理器
        audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

        // 获取控件实例
        imageView = findViewById(R.id.image);
        playBack = findViewById(R.id.playback);
        seekBar = findViewById(R.id.progress);
        loop = findViewById(R.id.loop);
        textView = findViewById(R.id.text);
        favorite = findViewById(R.id.favorite);

        appDatabase = AppDatabase.getDatabase(this);
        favoriteSoundsDao = appDatabase.favoriteSoundsDao();

        // 接收传递的 SoundItem 对象
        soundItemList = (SoundItem) getIntent().getSerializableExtra("1234");
        if (soundItemList == null) {
            return;
        }

        textView.setText(soundItemList.getTitle());

        // 检查数据库中是否存在该音频的收藏记录
        checkFavoriteStatus();

        //设置收藏点击事件
        favorite.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isFavorite = !isFavorite;
                updateFavoriteIcon();
                updateDatabase();
            }
        });

        // 设置循环图标的点击事件
        loop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isLooping = !isLooping;
                loop.setImageResource(isLooping ? R.drawable.true_loop : R.drawable.loop);
                if (mediaPlayer != null) {
                    mediaPlayer.setLooping(isLooping);
                }
            }
        });

        // 设置播放/暂停图标的点击事件
        playBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                playAudio();
            }
        });

        // 获取设备的最大音量值
        int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        // 设置SeekBar的最大值
        seekBar.setMax(maxVolume);

        // 获取当前音量值
        int currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        // 设置SeekBar的初始进度
        seekBar.setProgress(currentVolume);

        // 设置SeekBar监听器
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                // 调整音量
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, progress, 0);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                // 用户开始拖动进度条时执行的操作
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // 用户停止拖动进度条时执行的操作
            }
        });

        // 使用 Glide 加载图片
        Glide.with(MainApplication.getContext())
                .asDrawable()
                .skipMemoryCache(true)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .load(soundItemList.getPreUrl())
                .transform(new CenterCrop())
                .into(imageView);
    }

    private void checkFavoriteStatus() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 检查数据库中是否存在该音频的收藏记录
                FavoriteSounds favoriteSound = favoriteSoundsDao.getByPath(soundItemList.getMp3Url());
                isFavorite = favoriteSound != null;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        updateFavoriteIcon();
                    }
                });
            }
        }).start();
    }

    private void updateFavoriteIcon() {
        favorite.setImageResource(isFavorite ? R.drawable.favorite : R.drawable.unfavorite);
    }

    private void updateDatabase() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 判断是否收藏
                if (isFavorite) {
                    // 插入数据到数据库
                    FavoriteSounds favoriteSound = new FavoriteSounds(
                            soundItemList.getTitle(),
                            soundItemList.getMp3Url(),
                            soundItemList.getPreUrl()
                    );
                    favoriteSoundsDao.insertSound(favoriteSound);
                } else {
                    // 从数据库删除数据，先根据路径检索出要删除的对象
                    FavoriteSounds favoriteSound = favoriteSoundsDao.getByPath(soundItemList.getMp3Url());
                    if (favoriteSound != null) {
                        favoriteSoundsDao.delete(favoriteSound);
                    }
                }
            }
        }).start();
    }


    private void playAudio() {
        String audioUrl = soundItemList.getMp3Url(); // 获取音频的URL

        if (mediaPlayer == null) {
            // 如果MediaPlayer对象为空，则创建一个新的MediaPlayer对象
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); // 设置音频流类型为音乐

            try {
                mediaPlayer.setDataSource(audioUrl); // 设置音频数据源
                mediaPlayer.prepareAsync(); // 异步准备MediaPlayer

                // 设置MediaPlayer准备完成监听器
                mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mp) {
                        mediaPlayer.start(); // 开始播放音频
                        playBack.setImageResource(R.drawable.pause); // 播放时显示暂停图标
                        isPlaying = true; // 设置播放状态为正在播放
                        mediaPlayer.setLooping(isLooping); // 设置是否循环播放
                    }
                });

                // 设置MediaPlayer错误监听器
                mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                    @Override
                    public boolean onError(MediaPlayer mp, int what, int extra) {
                        Toast.makeText(PlaySoundActivity.this, "Error playing audio", Toast.LENGTH_SHORT).show(); // 显示错误提示
                        return false;
                    }
                });

                // 设置MediaPlayer播放完成监听器
                mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        if (!isLooping) {
                            playBack.setImageResource(R.drawable.playback); // 播放完成时显示播放图标
                            isPlaying = false; // 设置播放状态为未播放
                        }
                    }
                });

            } catch (IOException e) {
                e.printStackTrace(); // 打印异常堆栈信息
                Toast.makeText(PlaySoundActivity.this, "Error setting data source", Toast.LENGTH_SHORT).show(); // 显示错误提示
            }
        } else {
            // 如果MediaPlayer对象已经存在
            if (isPlaying) {
                mediaPlayer.pause(); // 暂停播放
                playBack.setImageResource(R.drawable.playback); // 暂停时显示播放图标
            } else {
                mediaPlayer.start(); // 继续播放
                playBack.setImageResource(R.drawable.pause); // 播放时显示暂停图标
            }
            isPlaying = !isPlaying; // 切换播放状态
        }
    }

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