package com.gh.gamecenter.manager;

import android.content.Context;

import com.gh.common.constant.Config;
import com.gh.gamecenter.core.utils.StringUtils;
import com.gh.gamecenter.common.utils.TimestampUtils;
import com.gh.gamecenter.core.utils.UrlFilterUtils;
import com.gh.gamecenter.common.retrofit.ObservableUtil;
import com.gh.gamecenter.common.retrofit.OkHttpCache;

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

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

import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;

/**
 * Created by LGT on 2016/11/16.
 */
public class VisitManager {

    private List<String> urlList;

    private VisitManager() {
        urlList = new ArrayList<>();
    }

    // 更新okhttp缓存数据
    public static void updateOkhttpCache(final Context context, final String news_id) {
        ObservableUtil.io(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> emitter) {
                String key = VisitManager.getInstance().getUrl(news_id);
                if (key == null) {
                    return;
                }
                key = TimestampUtils.addTimestamp(key);
                byte[] data = OkHttpCache.getCache(context, key);
                if (data != null) {
                    try {
                        JSONArray jsonArray = new JSONArray(new String(data));
                        JSONObject jsonObject;
                        for (int i = 0, size = jsonArray.length(); i < size; i++) {
                            jsonObject = jsonArray.getJSONObject(i);
                            if (jsonObject.getString("id").equals(news_id)) {
                                jsonObject.put("views", jsonObject.getInt("views") + 1);
                                break;
                            }
                        }
                        OkHttpCache.updateCache(context, key, jsonArray.toString().getBytes());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        }, null);
    }

    public String getUrl(String id) {
        for (int i = 0, size = urlList.size(); i < size; i++) {
            if (urlList.get(i).contains(id)) {
                return urlList.get(i);
            }
        }
        return null;
    }

    public static VisitManager getInstance() {
        return SingletonHolder.INSTANCE;
    }

    public void addUrl(String ids) {
        String url = StringUtils.buildString(Config.API_HOST, "articles/visits?filter=" + UrlFilterUtils.getFilterQuery("article_ids", ids));
        if (!urlList.contains(url)) {
            urlList.add(url);
        }
    }

    private static class SingletonHolder {
        private static final VisitManager INSTANCE = new VisitManager();
    }
}
