package com.pixelmintdrop.audio

import android.content.Context
import android.media.MediaPlayer
import android.media.AudioAttributes
import android.os.Build
import android.util.Log
import com.pixelmintdrop.R

class GameMusic(private val context: Context) {
    private var mediaPlayer: MediaPlayer? = null
    private var gameOverPlayer: MediaPlayer? = null
    private var isEnabled = true
    private var isPrepared = false
    
    init {
        try {
            setupMediaPlayer()
            setupGameOverPlayer()
        } catch (e: Exception) {
            Log.e("GameMusic", "Error initializing: ${e.message}")
        }
    }
    
    private fun setupMediaPlayer() {
        try {
            Log.d("GameMusic", "Setting up MediaPlayer")
            mediaPlayer = MediaPlayer.create(context, R.raw.game_music).apply {
                isLooping = true
                setVolume(0.5f, 0.5f)
                
                // Set audio attributes for better performance
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    setAudioAttributes(
                        AudioAttributes.Builder()
                            .setUsage(AudioAttributes.USAGE_GAME)
                            .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                            .build()
                    )
                }
                isPrepared = true
            }
            Log.d("GameMusic", "MediaPlayer setup complete")
        } catch (e: Exception) {
            Log.e("GameMusic", "Error setting up MediaPlayer", e)
            mediaPlayer = null
            isPrepared = false
        }
    }
    
    private fun setupGameOverPlayer() {
        try {
            Log.d("GameMusic", "Setting up GameOver MediaPlayer")
            gameOverPlayer = MediaPlayer.create(context, R.raw.game_over).apply {
                setVolume(1.0f, 1.0f)  // Increased from 0.7f to 1.0f for maximum volume
                
                // Set audio attributes for better performance
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    setAudioAttributes(
                        AudioAttributes.Builder()
                            .setUsage(AudioAttributes.USAGE_GAME)
                            .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                            .build()
                    )
                }
            }
            Log.d("GameMusic", "GameOver MediaPlayer setup complete")
        } catch (e: Exception) {
            Log.e("GameMusic", "Error setting up GameOver MediaPlayer", e)
            gameOverPlayer = null
        }
    }
    
    fun playGameOver() {
        if (isEnabled && gameOverPlayer != null) {
            try {
                Log.d("GameMusic", "Playing game over sound")
                // Temporarily lower background music volume
                mediaPlayer?.setVolume(0.2f, 0.2f)
                
                // Play game over sound
                gameOverPlayer?.start()
                
                // Restore background music volume after a delay
                gameOverPlayer?.setOnCompletionListener {
                    mediaPlayer?.setVolume(0.5f, 0.5f)
                }
            } catch (e: Exception) {
                Log.e("GameMusic", "Error playing game over sound: ${e.message}")
            }
        }
    }
    
    fun start() {
        if (isEnabled && mediaPlayer != null && isPrepared) {
            try {
                Log.d("GameMusic", "Starting music playback, isEnabled: $isEnabled")
                mediaPlayer?.start()
                Log.d("GameMusic", "Music playback started")
            } catch (e: Exception) {
                Log.e("GameMusic", "Error starting music: ${e.message}")
            }
        }
    }
    
    fun pause() {
        try {
            Log.d("GameMusic", "Pausing music playback")
            if (mediaPlayer?.isPlaying == true) {
                mediaPlayer?.pause()
            }
        } catch (e: Exception) {
            Log.e("GameMusic", "Error pausing music: ${e.message}")
        }
    }
    
    fun resume() {
        if (isEnabled && mediaPlayer != null && isPrepared) {
            try {
                Log.d("GameMusic", "Resuming music playback")
                mediaPlayer?.start()
            } catch (e: Exception) {
                Log.e("GameMusic", "Error resuming music: ${e.message}")
            }
        }
    }
    
    fun stop() {
        try {
            Log.d("GameMusic", "Stopping music playback")
            mediaPlayer?.stop()
            mediaPlayer?.prepare()
        } catch (e: Exception) {
            Log.e("GameMusic", "Error stopping music", e)
        }
    }
    
    fun setEnabled(enabled: Boolean) {
        Log.d("GameMusic", "Setting music enabled: $enabled")
        isEnabled = enabled
        
        if (!enabled && mediaPlayer?.isPlaying == true) {
            pause()
        }
    }
    
    fun isEnabled(): Boolean = isEnabled
    
    fun release() {
        try {
            Log.d("GameMusic", "Releasing MediaPlayer")
            mediaPlayer?.release()
            gameOverPlayer?.release()
            mediaPlayer = null
            gameOverPlayer = null
            isPrepared = false
        } catch (e: Exception) {
            Log.e("GameMusic", "Error releasing music: ${e.message}")
        }
    }
    
    /**
     * Ensures the main media player is prepared for playback.
     */
    fun prepareMusic() {
        if (mediaPlayer != null && !isPrepared) {
            try {
                mediaPlayer?.prepare()
                isPrepared = true
                Log.d("GameMusic", "MediaPlayer prepared successfully in prepareMusic()")
            } catch (e: IllegalStateException) {
                Log.e("GameMusic", "Error preparing MediaPlayer (already prepared?): ${e.message}")
                // Assume it's prepared if IllegalStateException is thrown
                isPrepared = true
            } catch (e: Exception) {
                Log.e("GameMusic", "Error preparing MediaPlayer", e)
                isPrepared = false
            }
        } else if (mediaPlayer != null && isPrepared) {
            Log.d("GameMusic", "MediaPlayer already prepared in prepareMusic()")
        }
    }
} 