package com.gh.common.util;


import android.content.Context;
import android.content.SharedPreferences;

import androidx.collection.ArrayMap;

import com.gh.gamecenter.entity.TagEntity;
import com.gh.gamecenter.common.retrofit.Response;
import com.gh.gamecenter.retrofit.RetrofitManager;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import retrofit2.HttpException;

public class TagUtils {

    private static TagUtils mInstance;

    private Context context;

    private ArrayMap<String, String> colorMap;
    private boolean isUpdate = false;

    private TagUtils(Context con) {
        this.context = con.getApplicationContext();
        initTag();
    }

    public static TagUtils getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new TagUtils(context);
        }
        return mInstance;
    }

    private void initTag() {
        colorMap = new ArrayMap<>();

        SharedPreferences sharedPreferences = context.getSharedPreferences("gh_tag", Context.MODE_PRIVATE);
        Set<String> set = sharedPreferences.getStringSet("tag", null);
        if (set == null) {
            getTag();
        } else {
            for (String str : set) {
                String[] platform = str.split("=");
                colorMap.put(platform[0], platform[1]);
            }
        }
    }

    public String getColor(String tag) {
        String color = colorMap.get(tag);
        if (color == null) {
            getTag();
        }
        return color;
    }

    public void getTag() {
        if (isUpdate) {
            return;
        }
        isUpdate = true;
        RetrofitManager.getInstance().getApi().getTags()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Response<List<TagEntity>>() {
                    @Override
                    public void onResponse(List<TagEntity> response) {
                        Set<String> tagSet = new HashSet<>();
                        for (TagEntity tagEntity : response) {
                            tagSet.add(tagEntity.getName() + "=" + tagEntity.getColor());
                        }
                        SharedPreferences sp = context.getSharedPreferences("gh_tag", Context.MODE_PRIVATE);
                        sp.edit().putStringSet("tag", tagSet).apply();
                        initTag();

                        isUpdate = false;
                    }

                    @Override
                    public void onFailure(HttpException e) {
                        isUpdate = false;
                    }
                });
    }

}
