package com.gh.gamecenter.manager;

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

import com.android.volley.Request;
import com.android.volley.Response;
import com.gh.base.AppController;
import com.gh.common.constant.Config;
import com.gh.common.util.Utils;
import com.gh.gamecenter.db.FilterDao;
import com.gh.gamecenter.db.info.FilterInfo;
import com.gh.gamecenter.volley.extended.JsonArrayExtendedRequest;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;

public class FilterManager {

	private FilterDao dao;
	private SharedPreferences sp;

	public FilterManager(Context context) {
		dao = new FilterDao(context);
		sp = context.getSharedPreferences(Config.PREFERENCE,
				Context.MODE_PRIVATE);
	}

	public void addFilter(String packageName) {
		dao.add(new FilterInfo(packageName));
	}

	public void addAllFilter(List<FilterInfo> list) {
		dao.addAll(list);
	}

	public void deleteGame(String packageName) {
		dao.delete(packageName);
	}

	public List<FilterInfo> getAllGame() {
		return dao.getAll();
	}

	public boolean isFilter(String packageName) {
		return dao.isFilter(packageName);
	}

	public void getFilterFromServer(final String today) {
		long skip = dao.getCount();
		JsonArrayExtendedRequest request = new JsonArrayExtendedRequest(Request.Method.GET,
				Config.HOST + "v1d45/support/package/unused?skip=" + skip, new JSONArray(),
				new Response.Listener<JSONArray>() {
					@Override
					public void onResponse(JSONArray response) {

						Utils.log("getFilterFromServer=" + response.toString());

						try {
							List<FilterInfo> list = new ArrayList<FilterInfo>();
							for (int i = 0, size = response.length(); i < size; i++) {
								list.add(new FilterInfo(response.getString(i)));
							}
							dao.addAll(list);
							sp.edit().putString("filter_time", today).apply();
							if (list.size() == 500){
								getFilterFromServer(today);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
				}, null);
		AppController.addToRequestQueue(request);
	}
}
