package com.idle.wall;
import android.content.Context;
import android.content.SharedPreferences;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

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

public class RecentManager {
    private static final String PREF_NAME = "recent_wallpapers";
    private static final String KEY_RECENT_LIST = "recent_list";
    private static RecentManager instance;
    private SharedPreferences sp;
    private Gson gson;

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

    public static synchronized RecentManager getInstance(Context context) {
        if (instance == null) {
            instance = new RecentManager(context.getApplicationContext());
        }
        return instance;
    }
    public void addRecentWallpaper(IdleWallpaper wallpaper) {
        List<IdleWallpaper> list = getRecentWallpapers();
        list.removeIf(item -> item.getId().equals(wallpaper.getId()));
        list.add(0, wallpaper);
        if (list.size() > 20) {
            list = list.subList(0, 20);
        }
        SharedPreferences.Editor editor = sp.edit();
        editor.putString(KEY_RECENT_LIST, gson.toJson(list));
        editor.apply();
    }

    public List<IdleWallpaper> getRecentWallpapers() {
        String json = sp.getString(KEY_RECENT_LIST, "");
        Type type = new TypeToken<ArrayList<IdleWallpaper>>() {}.getType();
        List<IdleWallpaper> list = gson.fromJson(json, type);
        return list == null ? new ArrayList<>() : list;
    }

    // 清空最近浏览记录
    public void clearRecentWallpapers() {
        SharedPreferences.Editor editor = sp.edit();
        editor.remove(KEY_RECENT_LIST);
        editor.apply();
    }
}