package com.snap.wall;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.snap.wall.Wallpaper;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class RecentWallpaperManager {
    private static final String TAG = "RecentWallpaperManager";
    private static final String PREF_NAME = "RecentWallpapers";
    private static final String KEY_RECENT_LIST = "recent_wallpaper_list";
    private static final int MAX_RECENT_COUNT = 20;

    private static RecentWallpaperManager instance;
    private SharedPreferences sp;
    private Gson gson;

    private RecentWallpaperManager(Context context) {
        sp = context.getApplicationContext().getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        gson = new Gson();
    }

    public static synchronized RecentWallpaperManager getInstance(Context context) {
        if (instance == null) {
            instance = new RecentWallpaperManager(context);
        }
        return instance;
    }

    // 添加浏览记录（核心：确保添加成功）
    public void addRecentWallpaper(Wallpaper wallpaper) {
        if (wallpaper == null || wallpaper.getId() == null) {
            Log.e(TAG, "添加失败：壁纸对象/ID为空");
            return;
        }

        List<Wallpaper> list = getRecentWallpapers();
        // 移除重复项
        list.removeIf(w -> w.getId().equals(wallpaper.getId()));
        // 添加到顶部
        list.add(0, wallpaper);
        // 限制数量
        if (list.size() > MAX_RECENT_COUNT) {
            list = list.subList(0, MAX_RECENT_COUNT);
        }

        // 保存到SP
        String json = gson.toJson(list);
        sp.edit().putString(KEY_RECENT_LIST, json).commit(); // 用commit确保立即保存
        Log.d(TAG, "添加成功：" + wallpaper.getTitle() + "，当前总数：" + list.size());
    }

    // 获取浏览记录（核心：确保读取成功）
    public List<Wallpaper> getRecentWallpapers() {
        String json = sp.getString(KEY_RECENT_LIST, "");
        Type type = new TypeToken<ArrayList<Wallpaper>>() {}.getType();
        List<Wallpaper> list = gson.fromJson(json, type);

        if (list == null) {
            list = new ArrayList<>();
            Log.d(TAG, "读取到空列表，初始化新列表");
        } else {
            Log.d(TAG, "读取到记录数：" + list.size());
        }
        return list;
    }

    // 清空记录（用于测试）
    public void clear() {
        sp.edit().remove(KEY_RECENT_LIST).commit();
        Log.d(TAG, "已清空所有记录");
    }
}