package com.demo.mylibrary;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.demo.mylibrary.api.PostHelper;
import com.demo.mylibrary.api.RequestManager;
import com.demo.mylibrary.bean.APPInfo;
import com.demo.mylibrary.bean.BehaviorInfo;
import com.demo.mylibrary.bean.PageInfo;
import com.demo.mylibrary.utils.DBUtils;
import com.demo.mylibrary.utils.DeviceUtils;
import com.demo.mylibrary.utils.NetworkUtils;

import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class TAnalytics {
    private static int versionCode;
    private static long startTime;
    private static Context mContext;
    private static DatabaseHelper dbHelper;
    private static final String TAG = "TAnalytics";
    private static String mUserId, deviceId, buildVersion, phoneBrand, phoneModel;

    /**
     * 初始化
     *
     * @param context
     */
    public static void init(Context context) {
        mContext = context;
        dbHelper = new DatabaseHelper(context, "Log.db", (SQLiteDatabase.CursorFactory) null, 1);
        versionCode = DeviceUtils.getVersionCode(context);
        deviceId = DeviceUtils.getDeviceId(context);
        buildVersion = DeviceUtils.getBuildVersion();
        phoneBrand = DeviceUtils.getPhoneBrand();
        phoneModel = DeviceUtils.getPhoneModel();
    }

    /**
     * 用户状态改变的时调用
     *
     * @param token
     * @param userId
     * @param userType
     */
    public static void loginStateChange(String token, String userId, int userType) {
        mUserId = userId;
        RequestManager.getInstance().setToken(token);
        APPInfo appInfo = new APPInfo();
        appInfo.setUserId(userId);
        appInfo.setUserType(userType);
        appInfo.setFromApp("Jicai");
        appInfo.setAppVersion(String.valueOf(versionCode));
        appInfo.setDeviceID(deviceId);
        appInfo.setSystemInfo(buildVersion);
        appInfo.setNetwork(NetworkUtils.getNetInfo(mContext));
        appInfo.setDevicePlatform(phoneBrand);
        appInfo.setDeviceVersion(phoneModel);

        PostHelper.postAppInfo(appInfo);
    }

    /**
     * 页面可见时调用
     *
     * @param pageID
     */
    public static void onPageStart(String pageID) {
        startTime = System.currentTimeMillis();
    }

    /**
     * 页面不可见时调用
     *
     * @param pageId
     * @param pageStatus
     * @param previous
     * @param funnelId
     */
    public static void onPageEnd(final String pageId, final String pageStatus, final String previous, final String funnelId) {
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> emitter) throws Exception {
                String netInfo = NetworkUtils.getNetInfo(mContext);
                emitter.onNext(netInfo);
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String netInfo) throws Exception {
                        List<PageInfo> pageList = DBUtils.queryPageTable(dbHelper);
                        Log.d(TAG, "netInfo" + netInfo + "====behaviorList.size" + pageList.size());
                        long endTime = System.currentTimeMillis();
                        if (netInfo.equals("WIFI")) {
                            if (pageList.size() > 0) {
                                PostHelper.postPgaeList(pageList);
                                DBUtils.deletePageCache(dbHelper);
                            } else {
                                PageInfo page = new PageInfo(mUserId, pageId, pageStatus, previous, funnelId, String.valueOf(startTime), String.valueOf(endTime));
                                PostHelper.postPage(page);
                            }
                        } else if (netInfo.equals("MOBILE")) {
                            if (pageList.size() > 0 && pageList.size() < 10) {
                                DBUtils.insertPageTable(dbHelper, mUserId, pageId, previous, pageStatus, funnelId, startTime, endTime);
                            } else {
                                DBUtils.deletePageCache(dbHelper);
                                DBUtils.insertPageTable(dbHelper, mUserId, pageId, previous, pageStatus, funnelId, startTime, endTime);
                            }
                        }

                    }
                });
    }

    /**
     * 点击事件时调用
     *
     * @param eventId
     * @param value
     */
    public static void onClick(final int eventId, final String value) {

        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> emitter) throws Exception {
                String netInfo = NetworkUtils.getNetInfo(mContext);
                emitter.onNext(netInfo);
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String netInfo) throws Exception {
                        List<BehaviorInfo> behaviorList = DBUtils.queryBehaviorTable(dbHelper);
                        Log.d(TAG, "netInfo" + netInfo + "====behaviorList.size" + behaviorList.size());
                        if (netInfo.equals("WIFI")) {
                            if (behaviorList.size() > 0) {
                                PostHelper.postBehaviorList(behaviorList);
                                DBUtils.deleteBehaviorCache(dbHelper);
                            } else {
                                BehaviorInfo behavior = new BehaviorInfo(mUserId, eventId, value, "", "");
                                PostHelper.postBehavior(behavior);
                            }
                        } else if (netInfo.equals("MOBILE")) {
                            if (behaviorList.size() > 0 && behaviorList.size() < 10) {
                                DBUtils.insertBehaviorTable(dbHelper, mUserId, eventId, value);
                            } else {
                                PostHelper.postBehaviorList(behaviorList);
                                DBUtils.deleteBehaviorCache(dbHelper);
                                DBUtils.insertBehaviorTable(dbHelper, mUserId, eventId, value);
                            }
                        }
                    }
                });
    }
}
