package com.pixelmintdrop.game

import android.content.Context
import android.content.SharedPreferences
import android.os.Bundle
import com.google.gson.Gson
import com.pixelmintdrop.audio.GameMusic
import com.pixelmintdrop.model.GameBoard
import com.pixelmintdrop.model.HighScoreManager
import com.pixelmintdrop.model.StatsManager

/**
 * Handles the game's lifecycle events to ensure proper resource management
 * and state saving/restoration.
 */
class GameLifecycleManager(private val context: Context) {
    private val sharedPreferences: SharedPreferences = 
        context.getSharedPreferences("com.com.pixelmintgames.pixelmintdrop.game_state", Context.MODE_PRIVATE)
    private val gson = Gson()
    
    /**
     * Save the current game state when the app is paused
     */
    fun saveGameState(
        gameBoard: GameBoard,
        currentScore: Long,
        currentLevel: Int,
        piecesPlaced: Int,
        gameStartTime: Long
    ) {
        val editor = sharedPreferences.edit()
        
        // Save primitive data
        editor.putLong("current_score", currentScore)
        editor.putInt("current_level", currentLevel)
        editor.putInt("pieces_placed", piecesPlaced)
        editor.putLong("game_start_time", gameStartTime)
        
        // Save complex GameBoard state - we don't serialize the GameBoard directly
        // Instead we save key properties that can be used to recreate the board state
        try {
            editor.putInt("board_level", gameBoard.level)
            editor.putInt("board_lines", gameBoard.lines)
            editor.putInt("board_score", gameBoard.score)
        } catch (e: Exception) {
            // If serialization fails, just clear the saved state
            editor.remove("board_level")
            editor.remove("board_lines")
            editor.remove("board_score")
        }
        
        editor.apply()
    }
    
    /**
     * Restore the saved game state when the app is resumed
     * Returns a bundle with the restored state or null if no state exists
     */
    fun restoreGameState(): Bundle? {
        // Check if we have a saved state
        if (!sharedPreferences.contains("current_score")) {
            return null
        }
        
        val bundle = Bundle()
        
        // Restore primitive data
        bundle.putLong("current_score", sharedPreferences.getLong("current_score", 0))
        bundle.putInt("current_level", sharedPreferences.getInt("current_level", 1))
        bundle.putInt("pieces_placed", sharedPreferences.getInt("pieces_placed", 0))
        bundle.putLong("game_start_time", sharedPreferences.getLong("game_start_time", 0))
        
        // We don't try to deserialize the GameBoard, as it's too complex
        // Instead, we'll create a new game board and apply saved properties later
        bundle.putInt("board_level", sharedPreferences.getInt("board_level", 1))
        bundle.putInt("board_lines", sharedPreferences.getInt("board_lines", 0))
        bundle.putInt("board_score", sharedPreferences.getInt("board_score", 0))
        
        return bundle
    }
    
    /**
     * Clears the saved game state
     */
    fun clearGameState() {
        sharedPreferences.edit().clear().apply()
    }
    
    /**
     * Handle activity pause
     */
    fun onPause(
        gameView: GameView?,
        gameMusic: GameMusic?,
        statsManager: StatsManager?,
        highScoreManager: HighScoreManager?
    ) {
        // Pause the game view
        gameView?.let {
            if (!it.isPaused && !it.isGameOver()) {
                it.pause()
            }
        }
        
        // Pause music
        gameMusic?.pause()
        
        // Save any pending stats and scores - these methods must be made public in their respective classes
        // or this functionality should be removed if those methods can't be accessed
        try {
            statsManager?.let { /* Call public save method if available */ }
            highScoreManager?.let { /* Call public save method if available */ }
        } catch (e: Exception) {
            // Log error but continue
        }
    }
    
    /**
     * Handle activity resume
     */
    fun onResume(
        gameView: GameView?,
        gameMusic: GameMusic?,
        isMusicEnabled: Boolean
    ) {
        // Resume music if enabled
        if (isMusicEnabled) {
            gameMusic?.resume()
        }
    }
    
    /**
     * Handle activity destroy
     */
    fun onDestroy(
        gameView: GameView?,
        gameMusic: GameMusic?,
        statsManager: StatsManager?,
        highScoreManager: HighScoreManager?
    ) {
        // Release resources
        gameView?.releaseResources()
        gameMusic?.releaseResources()
        
        // Save any pending data - these methods must be made public in their respective classes
        // or this functionality should be removed if those methods can't be accessed
        try {
            statsManager?.let { /* Call public save method if available */ }
            highScoreManager?.let { /* Call public save method if available */ }
        } catch (e: Exception) {
            // Log error but continue
        }
    }
} 