package com.mygdx.game;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Preferences;
import com.badlogic.gdx.utils.Array;
import java.util.Random;

// Система сохранения игры через LibGDX Preferences.
public class GameSave {
    private static final String PREF_NAME = "AbsurdCityBuilder";
    
    // Ключи для сохранения
    private static final String KEY_PLANET = "planet";
    private static final String KEY_TOTAL_BUILDINGS = "totalBuildings";
    private static final String KEY_EARTH_BUILDINGS = "earthBuildings";
    private static final String KEY_MARS_BUILDINGS = "marsBuildings";
    private static final String KEY_VENUS_BUILDINGS = "venusBuildings";
    private static final String KEY_LANGUAGE = "language";
    private static final String KEY_ACHIEVEMENTS = "achievements";
    private static final String KEY_CORRECT_STREAK = "correctStreak";
    private static final String KEY_VISITED_MARS = "visitedMars";
    private static final String KEY_VISITED_VENUS = "visitedVenus";
    private static final String KEY_BUILDINGS = "buildings";
    
    // Статистика для достижений
    private static int totalBuildings = 0;
    private static int earthBuildings = 0;
    private static int marsBuildings = 0;
    private static int venusBuildings = 0;
    private static int correctStreak = 0;
    private static boolean visitedMars = false;
    private static boolean visitedVenus = false;
    
    // Сохранить состояние игры
    public static void save(AbsurdCityBuilder1 game) {
        Preferences prefs = Gdx.app.getPreferences(PREF_NAME);
        
        // Сохраняем текущую планету
        prefs.putString(KEY_PLANET, game.getCurrentPlanet().name());
        
        // Сохраняем статистику
        prefs.putInteger(KEY_TOTAL_BUILDINGS, totalBuildings);
        prefs.putInteger(KEY_EARTH_BUILDINGS, earthBuildings);
        prefs.putInteger(KEY_MARS_BUILDINGS, marsBuildings);
        prefs.putInteger(KEY_VENUS_BUILDINGS, venusBuildings);
        prefs.putInteger(KEY_CORRECT_STREAK, correctStreak);
        prefs.putBoolean(KEY_VISITED_MARS, visitedMars);
        prefs.putBoolean(KEY_VISITED_VENUS, visitedVenus);
        
        // Сохраняем язык
        prefs.putString(KEY_LANGUAGE, Localization.getCurrentLanguage());
        
        // Сохраняем достижения
        prefs.putString(KEY_ACHIEVEMENTS, Achievements.getUnlockedAsString());
        
        prefs.flush();
        
        // Сохраняем здания отдельно
        saveBuildings(game.getBuildings());
    }
    
    // Загрузить состояние игры
    public static void load(AbsurdCityBuilder1 game) {
        Preferences prefs = Gdx.app.getPreferences(PREF_NAME);
        
        // Загружаем язык
        String language = prefs.getString(KEY_LANGUAGE, "ru");
        Localization.setLanguage(language);
        
        // Загружаем статистику
        totalBuildings = prefs.getInteger(KEY_TOTAL_BUILDINGS, 0);
        earthBuildings = prefs.getInteger(KEY_EARTH_BUILDINGS, 0);
        marsBuildings = prefs.getInteger(KEY_MARS_BUILDINGS, 0);
        venusBuildings = prefs.getInteger(KEY_VENUS_BUILDINGS, 0);
        correctStreak = prefs.getInteger(KEY_CORRECT_STREAK, 0);
        visitedMars = prefs.getBoolean(KEY_VISITED_MARS, false);
        visitedVenus = prefs.getBoolean(KEY_VISITED_VENUS, false);
        
        // Загружаем достижения
        String achievementsStr = prefs.getString(KEY_ACHIEVEMENTS, "");
        Achievements.loadFromString(achievementsStr);
        
        // Загружаем планету для продолжения
        String planetStr = prefs.getString(KEY_PLANET, "EARTH");
        try {
            Planet planet = Planet.valueOf(planetStr);
            game.setCurrentPlanet(planet);
        } catch (Exception e) {
            game.setCurrentPlanet(Planet.EARTH);
        }
    }
    
    /**
     * Проверить, есть ли сохранение
     */
    public static boolean hasSave() {
        Preferences prefs = Gdx.app.getPreferences(PREF_NAME);
        // Есть сохранение если есть здания ИЛИ статистика
        String buildings = prefs.getString(KEY_BUILDINGS, "");
        int totalBuilt = prefs.getInteger(KEY_TOTAL_BUILDINGS, 0);
        return !buildings.isEmpty() || totalBuilt > 0;
    }
    
    /**
     * Удалить сохранение
     */
    public static void deleteSave() {
        Preferences prefs = Gdx.app.getPreferences(PREF_NAME);
        prefs.clear();
        prefs.flush();
        
        resetAll();
    }
    
    /**
     * Сбросить всю статистику (для новой игры)
     */
    public static void resetAll() {
        totalBuildings = 0;
        earthBuildings = 0;
        marsBuildings = 0;
        venusBuildings = 0;
        correctStreak = 0;
        visitedMars = false;
        visitedVenus = false;
        
        // Сохраняем сброс
        Preferences prefs = Gdx.app.getPreferences(PREF_NAME);
        prefs.putInteger(KEY_TOTAL_BUILDINGS, 0);
        prefs.putInteger(KEY_EARTH_BUILDINGS, 0);
        prefs.putInteger(KEY_MARS_BUILDINGS, 0);
        prefs.putInteger(KEY_VENUS_BUILDINGS, 0);
        prefs.putInteger(KEY_CORRECT_STREAK, 0);
        prefs.putBoolean(KEY_VISITED_MARS, false);
        prefs.putBoolean(KEY_VISITED_VENUS, false);
        prefs.putString(KEY_PLANET, "EARTH");
        prefs.putString(KEY_ACHIEVEMENTS, "");
        prefs.putString(KEY_BUILDINGS, ""); // Очищаем здания
        prefs.flush();
    }
    
    /**
     * Загрузить только настройки (язык) при старте
     */
    public static void loadSettings() {
        Preferences prefs = Gdx.app.getPreferences(PREF_NAME);
        String language = prefs.getString(KEY_LANGUAGE, "ru");
        Localization.setLanguage(language);
        
        // Загружаем достижения
        String achievementsStr = prefs.getString(KEY_ACHIEVEMENTS, "");
        Achievements.loadFromString(achievementsStr);
        
        // Загружаем статистику
        totalBuildings = prefs.getInteger(KEY_TOTAL_BUILDINGS, 0);
        earthBuildings = prefs.getInteger(KEY_EARTH_BUILDINGS, 0);
        marsBuildings = prefs.getInteger(KEY_MARS_BUILDINGS, 0);
        venusBuildings = prefs.getInteger(KEY_VENUS_BUILDINGS, 0);
        correctStreak = prefs.getInteger(KEY_CORRECT_STREAK, 0);
        visitedMars = prefs.getBoolean(KEY_VISITED_MARS, false);
        visitedVenus = prefs.getBoolean(KEY_VISITED_VENUS, false);
    }
    
    /**
     * Сохранить настройки и статистику
     */
    public static void saveSettings() {
        Preferences prefs = Gdx.app.getPreferences(PREF_NAME);
        
        // Язык
        prefs.putString(KEY_LANGUAGE, Localization.getCurrentLanguage());
        
        // Достижения
        prefs.putString(KEY_ACHIEVEMENTS, Achievements.getUnlockedAsString());
        
        // Статистика
        prefs.putInteger(KEY_TOTAL_BUILDINGS, totalBuildings);
        prefs.putInteger(KEY_EARTH_BUILDINGS, earthBuildings);
        prefs.putInteger(KEY_MARS_BUILDINGS, marsBuildings);
        prefs.putInteger(KEY_VENUS_BUILDINGS, venusBuildings);
        prefs.putInteger(KEY_CORRECT_STREAK, correctStreak);
        prefs.putBoolean(KEY_VISITED_MARS, visitedMars);
        prefs.putBoolean(KEY_VISITED_VENUS, visitedVenus);
        
        prefs.flush();
    }
    
    /**
     * Сохранить текущую планету
     */
    public static void savePlanet(Planet planet) {
        Preferences prefs = Gdx.app.getPreferences(PREF_NAME);
        prefs.putString(KEY_PLANET, planet.name());
        prefs.flush();
    }
    
    /**
     * Сохранить здания
     * Формат: type|x|y|width|height|planetIndex|progress;type|x|y|...
     */
    public static void saveBuildings(Array<Building> buildings) {
        if (buildings == null || buildings.size == 0) {
            Preferences prefs = Gdx.app.getPreferences(PREF_NAME);
            prefs.putString(KEY_BUILDINGS, "");
            prefs.flush();
            return;
        }
        
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < buildings.size; i++) {
            Building b = buildings.get(i);
            if (i > 0) sb.append(";");
            sb.append(b.type).append("|");
            sb.append((int)b.x).append("|");
            sb.append((int)b.y).append("|");
            sb.append((int)b.width).append("|");
            sb.append((int)b.height).append("|");
            sb.append(b.planetIndex).append("|");
            sb.append(b.constructionProgress);
        }
        
        Preferences prefs = Gdx.app.getPreferences(PREF_NAME);
        prefs.putString(KEY_BUILDINGS, sb.toString());
        prefs.flush();
    }
    
    // загружаем здания
    public static void loadBuildings(Array<Building> buildings, Array<Citizen> citizens, Random random) {
        buildings.clear();
        citizens.clear();
        
        Preferences prefs = Gdx.app.getPreferences(PREF_NAME);
        String data = prefs.getString(KEY_BUILDINGS, "");
        
        if (data.isEmpty()) {
            return;
        }
        
        String[] buildingData = data.split(";");
        for (String bd : buildingData) {
            String[] parts = bd.split("\\|");
            if (parts.length >= 7) {
                try {
                    String type = parts[0];
                    float x = Float.parseFloat(parts[1]);
                    float y = Float.parseFloat(parts[2]);
                    float width = Float.parseFloat(parts[3]);
                    float height = Float.parseFloat(parts[4]);
                    int planetIndex = Integer.parseInt(parts[5]);
                    int progress = Integer.parseInt(parts[6]);
                    
                    Planet planet = Planet.values()[planetIndex];
                    Building building = new Building(type, x, y, width, height, random, planet);
                    
                    // Восстанавливаем прогресс
                    for (int i = 0; i < progress; i++) {
                        building.addBlock();
                    }
                    
                    buildings.add(building);
                    
                    // Создаём жителей для завершённых зданий
                    if (building.isComplete()) {
                        building.createCitizensForBuilding(citizens, random);
                    }
                } catch (Exception e) {
                    // Пропускаем битые данные
                }
            }
        }
    }
    
    // ==================== СТАТИСТИКА ====================
    
    public static void onBuildingComplete(Planet planet) {
        totalBuildings++;
        switch (planet) {
            case EARTH:
                earthBuildings++;
                break;
            case MARS:
                marsBuildings++;
                break;
            case VENUS:
                venusBuildings++;
                break;
        }
    }
    
    public static void onCorrectAnswer() {
        correctStreak++;
    }
    
    public static void onWrongAnswer() {
        correctStreak = 0;
    }
    
    // Алиасы для AnswerChecker
    public static void addCorrectAnswer() {
        onCorrectAnswer();
    }
    
    public static void resetCorrectStreak() {
        onWrongAnswer();
    }
    
    public static void addBuilding(Planet planet) {
        onBuildingComplete(planet);
    }
    
    public static void onVisitPlanet(Planet planet) {
        switch (planet) {
            case MARS:
                visitedMars = true;
                break;
            case VENUS:
                visitedVenus = true;
                break;
            default:
                break;
        }
    }
    
    // ==================== ГЕТТЕРЫ ДЛЯ ДОСТИЖЕНИЙ ====================
    
    public static int getTotalBuildings() {
        return totalBuildings;
    }
    
    public static int getEarthBuildings() {
        return earthBuildings;
    }
    
    public static int getMarsBuildings() {
        return marsBuildings;
    }
    
    public static int getVenusBuildings() {
        return venusBuildings;
    }
    
    public static int getCorrectStreak() {
        return correctStreak;
    }
    
    public static boolean hasVisitedMars() {
        return visitedMars;
    }
    
    public static boolean hasVisitedVenus() {
        return visitedVenus;
    }
    
    public static boolean hasVisitedAllPlanets() {
        return visitedMars && visitedVenus;
    }
}
