package org.cocos2dx.javascript.thirdSdk.thinkingdata;

import android.util.Log;

import org.cocos2dx.javascript.AppActivity;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import cn.thinkingdata.android.TDConfig;
import cn.thinkingdata.android.ThinkingAnalyticsSDK;

public class TDSDKMgr {

    /** 单例模式 */
    private static TDSDKMgr mInstace = null;

    public static TDSDKMgr getInstance() {
        if (null == mInstace) {
            mInstace = new TDSDKMgr();
        }
        return mInstace;
    }

    private final String TA_APP_ID = "ee451573e55144548a0f128467c7f0f7";
    private final String TA_SERVER_URL = "https://taapi.mokagm.com/";
    private ThinkingAnalyticsSDK TDInstance = null;

    public AppActivity appActivity = null;

    public void initSdk(AppActivity appActivity) {
        this.appActivity = appActivity;

        // 获取 TDConfig 实例
        TDConfig config = TDConfig.getInstance(this.appActivity, TA_APP_ID, TA_SERVER_URL);
        // 初始化 SDK
        this.TDInstance = ThinkingAnalyticsSDK.sharedInstance(config);
    }

    public void setTAEvent(String eventID, String des) {
        if (this.TDInstance == null) {
            return;
        }
        try {
            JSONObject properties = new JSONObject();
            properties.put("eventID", eventID);
            properties.put("des", des);
            TDInstance.track(eventID, properties);
            Log.d("setTAEvent   ", "setTAEvent: " + eventID);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /** -- 数数相关 --*/
    public void setTAEventRegister(){
        try {
            JSONObject properties = new JSONObject();
            properties.put("register","register");
            TDInstance.track("register",properties);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        try {
            String cTime = curTime();
            JSONObject properties = new JSONObject();
            properties.put("RegTime", cTime);
            properties.put("role_create_time", cTime);
            TDInstance.user_setOnce(properties);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private String curTime(){
        String pattern = "yyyy-MM-dd HH:mm:ss.SSS";
        SimpleDateFormat sDateFormat = new SimpleDateFormat(pattern, Locale.CHINA);
        String timeString = sDateFormat.format(new Date());

        Log.d("TAEvent", "setTAEventUser: "+timeString);
        return timeString;
    }
}
