package com.ygtx.emcs.comm;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;

import java.util.concurrent.atomic.AtomicReference;

public class CacheService {
    private static CacheService cacheServices;
    private Context context;

    public static CacheService getInstance(Context context){
        if(cacheServices == null){
            cacheServices = new CacheService();
            cacheServices.context = context;
        }
        return cacheServices;
    }

    public void saveCache(String position, String key, String value) {
        new Thread(()->{
            SharedPreferences mySharedPreferences = context.getSharedPreferences(position,
                    Activity.MODE_PRIVATE);
            SharedPreferences.Editor editor = mySharedPreferences.edit();
            // 用putString的方法保存数据
            editor.putString(key, value);
            // 提交当前数据
            editor.commit();
        }).start();
    }

    public void clear(String position) {
        new Thread(()-> {
            SharedPreferences preferences = context.getSharedPreferences(position, Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = preferences.edit();
            editor.clear();
            editor.commit();
        }).start();
    }

    public String getCache(String position, String key) {
        AtomicReference<String> val = new AtomicReference<>("");
        Thread thread = new Thread(()->{
            SharedPreferences sharedPreferences = context.getSharedPreferences(position,
                    Activity.MODE_PRIVATE);
            // 使用getString方法获得value，注意第2个参数是value的默认值
            val.set(sharedPreferences.getString(key, ""));
        });
        try{
            thread.start();
            thread.join();
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return val.get();
    }
}
