package com.oo.seex.oo_statistics_lib;

import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.os.HandlerThread;
import android.text.TextUtils;

import com.oo.seex.oo_statistics_lib.bean.ActivityStaBean;
import com.oo.seex.oo_statistics_lib.bean.EventStaBean;
import com.oo.seex.oo_statistics_lib.bean.FragmentBean;
import com.oo.seex.oo_statistics_lib.bean.StatistivsBean;
import com.oo.seex.oo_statistics_lib.constant.OOConstant;
import com.oo.seex.oo_statistics_lib.dao.SaveInfo;
import com.oo.seex.oo_statistics_lib.dao.UploadNativeData;
import com.oo.seex.oo_statistics_lib.getjsonobject.GetJson;
import com.oo.seex.oo_statistics_lib.network.EventController;
import com.oo.seex.oo_statistics_lib.network.NetworkUitlity;
import com.oo.seex.oo_statistics_lib.utils.CommonUtil;
import com.oo.seex.oo_statistics_lib.utils.MyCrashHandler;
import com.oo.seex.oo_statistics_lib.utils.SharePreferenceUtils;

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

/**
 * Created by xucon on 2018/1/5.
 */

public class DataDeal {
	/**
	 * 我们在这里专门创建的消息发送器 并不是存在主线程中的 所以并不会因为UI线程的崩溃而停止
	 */
	private  Handler handler;

	private  Map<String, ActivityStaBean> activityMap = new HashMap<String, ActivityStaBean>();

	private  Map<String, FragmentBean> fragmentMap = new HashMap<String, FragmentBean>();

	private static DataDeal sDataDeal = new DataDeal();

	private DataDeal(){
		initHandler();
	}

	private void initHandler(){
		if(handler == null) {
			HandlerThread localHandlerThread = new HandlerThread("OOAgent");
			localHandlerThread.start();
			handler = new Handler(localHandlerThread.getLooper());
		}
	}

	public static DataDeal getInstance(){
		return sDataDeal;
	}

	public void dealActivityResume(final Activity activity){
		try {
			ActivityStaBean activityStaBean = new ActivityStaBean();
			String activities = activity.getLocalClassName();
			activityStaBean.setActivities(activity.getLocalClassName());
			activityStaBean.setParent_activity(activity.getComponentName().getClassName());
			activityStaBean.setStart_millis(String.valueOf(CommonUtil.getTime()));
			activityMap.put(activities, activityStaBean);
		}catch (Exception e){
			e.printStackTrace();
		}
	}

	public void dealActivityPause(final Activity activity){
		saveCloseTime(activity);
		String activities = activity.getLocalClassName();
		final ActivityStaBean activityStaBean = activityMap.get(activities);
		if(activityStaBean == null){
			return;
		}
		activityMap.remove(activities);
		if (activityStaBean != null && !TextUtils.isEmpty(activityStaBean.getStart_millis())) {
			Runnable postOnPauseinfoRunnable = new Runnable() {
				@Override
				public void run() {
					try {
						long end = CommonUtil.getTime(); //结束时间
						activityStaBean.setEnd_millis(String.valueOf(end));
						long duration = end - Long.parseLong(activityStaBean.getStart_millis());   //  在这个页面的停留时间
						activityStaBean.setDuration(String.valueOf(duration));
						String appkey = CommonUtil.getAppKey(activity.getApplicationContext());
						activityStaBean.setAppkey(appkey);
						activityStaBean.setDevice_id(Build.SERIAL);
						activityStaBean.setVersion(CommonUtil.getVersion(activity.getApplicationContext()));
						final StatistivsBean info = new StatistivsBean();
						info.setActivityInfo(activityStaBean);
						if (CommonUtil.isNetworkAvailable(activity.getApplicationContext())) {
							NetworkUitlity.getInstance().requestPost(OOConstant.preUrl + OOConstant.activityUrl,
									GetJson.getActivityParams(activityStaBean),
									activity.getApplicationContext(), new NetworkUitlity.NetListener() {
										@Override
										public void succee() {}
										@Override
										public void error() {
											saveInfoToFile("activityInfo", info, activity.getApplicationContext());
										}
									});//访问网络
						} else {
							saveInfoToFile("activityInfo", info, activity.getApplicationContext());
						}
					}catch (Exception e){
						e.printStackTrace();
					}
				}
			};
			handler.post(postOnPauseinfoRunnable);
		}
	}

	/**
	 * 发送这个页面的本次统计(fragment）
	 *
	 */
	public void dealPauseFragment(final Activity activity,final String fragmentName) {
		final FragmentBean fragmentBean = fragmentMap.get(fragmentName);
		if (fragmentBean == null) {
			return;
		}
		fragmentMap.remove(fragmentName);
		Runnable postOnPauseinfoRunnable = new Runnable() {
			@Override
			public void run() {
				try {
					long endTime = CommonUtil.getTime();
					fragmentBean.setFragment_end_millis(String.valueOf(endTime));  //当前时间的年月日形式
					fragmentBean.setFragment_end(endTime); //结束时间
					fragmentBean.setFragment_duration(fragmentBean.getFragment_end() - fragmentBean.getFragment_start() + "");   //  在这个页面的停留时间
					fragmentBean.setActivity(activity.getLocalClassName());
					String appkey = CommonUtil.getAppKey(activity);
					fragmentBean.setAppkey(appkey);
					fragmentBean.setDevice_id(Build.SERIAL);
					fragmentBean.setVersion(CommonUtil.getVersion(activity.getApplicationContext()));

					final StatistivsBean info = new StatistivsBean();
					info.setFragmentInfo(fragmentBean);
					//发送统计结果
					if (CommonUtil.isNetworkAvailable(activity.getApplicationContext())) {
						NetworkUitlity.getInstance().requestPost(OOConstant.preUrl + OOConstant.fragmentUrl,
								GetJson.getFragmentParams(fragmentBean), activity.getApplicationContext(),
								new NetworkUitlity.NetListener() {
									@Override
									public void succee() {
									}

									@Override
									public void error() {
										saveInfoToFile("fragmentInfo", info, activity.getApplicationContext());
									}
								});//访问网络
					} else {
						saveInfoToFile("fragmentInfo", info, activity.getApplicationContext());
					}
				}catch (Exception e){
					e.printStackTrace();
				}
			}
		};
		handler.post(postOnPauseinfoRunnable);
	}

	/**
	 * 开始统计这个页面（fragment）
	 *
	 */
	public void dealResumeFragment(final Context context,String fragmentName) {
		try {
			FragmentBean fragmentBean = new FragmentBean();
			long startTime = CommonUtil.getTime();
			fragmentBean.setFragment_start_millis(String.valueOf(startTime));
			fragmentBean.setFragment_start(startTime);
			fragmentBean.setFragments(fragmentName);
			fragmentMap.put(fragmentName, fragmentBean);
		} catch (Exception e) {
			CommonUtil.printLog(e);
		}
	}

	private void saveCloseTime(Context context) {
		try {
			SharePreferenceUtils localSharedPreferences = SharePreferenceUtils.getInstance(context);
			localSharedPreferences.saveLong("application_close", CommonUtil.getTime());
		}catch (Exception e){
			e.printStackTrace();
		}
	}

	private void saveStartTime(Context context) {
		try {
			SharePreferenceUtils localSharedPreferences = SharePreferenceUtils.getInstance(context);
			localSharedPreferences.saveLong("application_start", CommonUtil.getTime());
		}catch (Exception e){
			e.printStackTrace();
		}
	}

	private long getCloseTime(Context context) {
		try {
			SharePreferenceUtils localSharedPreferences = SharePreferenceUtils.getInstance(context);
			return localSharedPreferences.getLong("application_close", CommonUtil.getTime());
		}catch (Exception e){
			e.printStackTrace();
			return CommonUtil.getTime();
		}
	}

	private long getStartTime(Context context) {
		try{
			SharePreferenceUtils localSharedPreferences = SharePreferenceUtils.getInstance(context);
			return localSharedPreferences.getLong("application_start", CommonUtil.getTime());
		}catch (Exception e){
			e.printStackTrace();
			return CommonUtil.getTime();
		}
	}

	/**
	 * @param mContext
	 * @param aname    自定义事件的标示  aname
	 * @param label    事件中的子标签的标示，用来统计比例
	 * @param acc      计数器，多次点击我们可以只算一次；但是这里需要用户自己维护一个计数器，
	 */
	public void onEvent(final Context mContext, final String aname, final String label, final Map<String, String> remarks, final int acc) {
		initHandler();
		if(handler != null) {
			Runnable postEventRunnable = new Runnable() {
				@Override
				public void run() {
					EventController.postEventInfo(handler, mContext, new EventStaBean(aname, label, acc + "", mContext, remarks));
				}
			};
			handler.post(postEventRunnable);
		}else{
			CommonUtil.printLog(CommonUtil.getActivityName(mContext), "handler--null");
		}
	}
	/**
	 * 保存信息到文件 我们在没有网络的时候，或者直接传送失败的时候我们就会将这部分的数据缓存到我们的数据库中
	 *
	 * @param type
	 * @param info
	 * @param context
	 */
	private void saveInfoToFile(String type, StatistivsBean info, Context context) {
		initHandler();
		if (handler != null) {
			info.setType(type);
			handler.post(new SaveInfo(context, info));
		} else {
			CommonUtil.printLog(CommonUtil.getActivityName(context), "handler--null");
		}
	}

	public void initShincAgent(final Context context, String deviceId) {
		onError(context);
		if (!TextUtils.isEmpty(deviceId)) {
			SharePreferenceUtils.getInstance(context).setDeviceId(deviceId);
		}
		UploadNativeData.getInstance().synNativeData(context.getApplicationContext());
	}

	/**
	 * 设置当线程由于未捕获到异常而突然终止，并且没有为该线程定义其他处理程序时所调用的默认处理程序。
	 * 这里就是创建子线程监视整个应用一旦发生崩溃，我们就将崩溃原因抓出来并且做相关操作
	 *
	 * @param mContext
	 */
	private void onError(final Context mContext) {
		initHandler();
		if(handler != null) {
			Thread thread = new Thread(new Runnable() {
				@Override
				public void run() {
					MyCrashHandler crashHandler = MyCrashHandler.getInstance();
					crashHandler.init(mContext.getApplicationContext(), handler);
					//捕获全局异常
					Thread.setDefaultUncaughtExceptionHandler(crashHandler);
				}
			});
			handler.post(thread);
		}
	}

}
