package com.pixelmintdrop.model

import android.content.Context
import android.content.SharedPreferences
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import java.lang.reflect.Type

class HighScoreManager(private val context: Context) {
    private val prefs: SharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
    private val gson = Gson()
    private val type: Type = object : TypeToken<List<HighScore>>() {}.type
    private val googlePlayGamesManager = GooglePlayGamesManager(context)

    companion object {
        private const val PREFS_NAME = "pixelmintdrop_highscores"
        private const val KEY_HIGHSCORES = "highscores"
        private const val MAX_HIGHSCORES = 5
    }

    fun getHighScores(): List<HighScore> {
        val json = prefs.getString(KEY_HIGHSCORES, null)
        return if (json != null) {
            gson.fromJson(json, type)
        } else {
            emptyList()
        }
    }

    fun addHighScore(highScore: HighScore) {
        // Save to local high scores
        val currentScores = getHighScores().toMutableList()
        currentScores.add(highScore)
        
        // Sort by score (descending) and keep only top 5
        currentScores.sortByDescending { it.score }
        val topScores = currentScores.take(MAX_HIGHSCORES)
        
        // Save to SharedPreferences
        val json = gson.toJson(topScores)
        prefs.edit().putString(KEY_HIGHSCORES, json).apply()
        
        // Submit to Google Play Games leaderboard if signed in
        submitScoreToGooglePlay(highScore.score)
    }

    fun isHighScore(score: Int): Boolean {
        val currentScores = getHighScores()
        return currentScores.size < MAX_HIGHSCORES || 
               score > (currentScores.lastOrNull()?.score ?: 0)
    }
    
    // Submit score to Google Play Games leaderboard
    private fun submitScoreToGooglePlay(score: Int) {
        // We don't have an activity here, so we can't submit the score directly
        // The score will be submitted later when an activity is available
        try {
            googlePlayGamesManager.submitScore(score.toLong(), null)
        } catch (e: Exception) {
            // Log error but don't crash
            android.util.Log.e("HighScoreManager", "Error submitting score to leaderboard", e)
        }
    }
    
    // Method to check if user is signed in to Google Play Games
    fun isGooglePlaySignedIn(): Boolean {
        return googlePlayGamesManager.isSignedIn()
    }
    
    // Get Google Play Games manager
    fun getGooglePlayGamesManager(): GooglePlayGamesManager {
        return googlePlayGamesManager
    }
} 