package com.example.gameofmoon.data

import android.content.Context
import android.content.SharedPreferences
import com.example.gameofmoon.model.GameState
import kotlinx.serialization.encodeToString
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json

/**
 * 游戏保存管理器
 * 使用SharedPreferences进行简单的数据持久化
 */
class GameSaveManager(private val context: Context) {
    
    private val prefs: SharedPreferences = context.getSharedPreferences(
        "time_cage_save", Context.MODE_PRIVATE
    )
    
    private val json = Json {
        ignoreUnknownKeys = true
        encodeDefaults = true
    }
    
    /**
     * 保存游戏状态
     */
    fun saveGame(
        gameState: GameState,
        currentNodeId: String,
        dialogueHistory: List<String> = emptyList()
    ): Boolean {
        return try {
            val gameStateJson = json.encodeToString(gameState)
            val dialogueJson = json.encodeToString(dialogueHistory)
            
            prefs.edit()
                .putString(KEY_GAME_STATE, gameStateJson)
                .putString(KEY_CURRENT_NODE, currentNodeId)
                .putString(KEY_DIALOGUE_HISTORY, dialogueJson)
                .putLong(KEY_SAVE_TIME, System.currentTimeMillis())
                .apply()
            
            true
        } catch (e: Exception) {
            e.printStackTrace()
            false
        }
    }
    
    /**
     * 加载游戏状态
     */
    fun loadGame(): SaveData? {
        return try {
            val gameStateJson = prefs.getString(KEY_GAME_STATE, null) ?: return null
            val currentNodeId = prefs.getString(KEY_CURRENT_NODE, null) ?: return null
            val dialogueJson = prefs.getString(KEY_DIALOGUE_HISTORY, "[]")!!
            val saveTime = prefs.getLong(KEY_SAVE_TIME, 0L)
            
            val gameState = json.decodeFromString<GameState>(gameStateJson)
            val dialogueHistory = json.decodeFromString<List<String>>(dialogueJson)
            
            SaveData(
                gameState = gameState,
                currentNodeId = currentNodeId,
                dialogueHistory = dialogueHistory,
                saveTime = saveTime
            )
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }
    
    /**
     * 检查是否有保存的游戏
     */
    fun hasSavedGame(): Boolean {
        return prefs.contains(KEY_GAME_STATE)
    }
    
    /**
     * 删除保存的游戏
     */
    fun deleteSave(): Boolean {
        return try {
            prefs.edit()
                .remove(KEY_GAME_STATE)
                .remove(KEY_CURRENT_NODE)
                .remove(KEY_DIALOGUE_HISTORY)
                .remove(KEY_SAVE_TIME)
                .apply()
            true
        } catch (e: Exception) {
            false
        }
    }
    
    /**
     * 获取保存时间的格式化字符串
     */
    fun getSaveTimeString(): String? {
        val saveTime = prefs.getLong(KEY_SAVE_TIME, 0L)
        return if (saveTime > 0) {
            val date = java.util.Date(saveTime)
            java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.getDefault())
                .format(date)
        } else {
            null
        }
    }
    
    companion object {
        private const val KEY_GAME_STATE = "game_state"
        private const val KEY_CURRENT_NODE = "current_node"
        private const val KEY_DIALOGUE_HISTORY = "dialogue_history"
        private const val KEY_SAVE_TIME = "save_time"
    }
}

/**
 * 保存数据结构
 */
data class SaveData(
    val gameState: GameState,
    val currentNodeId: String,
    val dialogueHistory: List<String>,
    val saveTime: Long
)
