package com.gh.gamecenter.manager;

import android.content.Context;

import com.gh.gamecenter.core.AppExecutor;
import com.gh.gamecenter.common.exposure.meta.MetaUtil;
import com.gh.gamecenter.common.loghub.LoghubUtils;
import com.gh.gamecenter.common.utils.Installation;
import com.gh.common.util.LogUtils;
import com.gh.common.util.PackageUtils;
import com.halo.assistant.HaloApp;
import com.lightgame.utils.Utils;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class DataCollectionManager {

    private Context mContext;

    private DataCollectionManager() {
        mContext = HaloApp.getInstance().getApplicationContext();
    }

    public static void onEvent(Context context, String type, Map<String, Object> map, boolean isUpload) {
        AppExecutor.getLogExecutor().execute(() -> {
            map.put("createdOn", Utils.getTime(context));
            DataCollectionManager.getInstance().realTimeUpload(type, map);
        });
    }

    /*
     * 实时上传
     */
    private void realTimeUpload(final String type, Map<String, Object> map) {
        String version = PackageUtils.getGhVersionName();
        String user = Installation.getUUID(mContext);
        String channel = HaloApp.getInstance().getChannel();
        map.put("version", version);
        map.put("resu", user);
        map.put("jnfj", MetaUtil.getBase64EncodedIMEI());
        map.put("channel", channel);
        map.put("updateOn", Utils.getTime(HaloApp.getInstance().getApplication()));
        map.put("type", type);

        Map<String, Object> paramsWrapper = new HashMap<>();
        if ("news".equals(type) || "download".equals(type) || "search".equals(type)) {
            paramsWrapper.put("meta", LogUtils.getMetaObject().toString());
        }
        paramsWrapper.put("topic", type);
        paramsWrapper.put("content", new JSONObject(map).toString());
        paramsWrapper.put("time", Utils.getTime(HaloApp.getInstance().getApplication()));

        LoghubUtils.log(new JSONObject(paramsWrapper), "collection", true);
    }

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

    public static void onEvent(Context context, String type, Map<String, Object> map) {
        AppExecutor.getLogExecutor().execute(() -> {
            map.put("createdOn", Utils.getTime(context));
            DataCollectionManager.getInstance().realTimeUpload(type, map);
        });
    }

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