package com.mjsheng.myappstore.base;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.support.multidex.MultiDexApplication;
import android.util.Log;


import com.alibaba.fastjson.JSON;
import com.arialyy.aria.core.Aria;
import com.blankj.utilcode.util.PathUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheEntity;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.cookie.store.PersistentCookieStore;
import com.lzy.okserver.download.DownloadInfo;
import com.lzy.okserver.download.DownloadManager;
import com.lzy.okserver.download.DownloadService;
import com.mjsheng.myappstore.R;
import com.mjsheng.myappstore.Statistics.AppInformation;
import com.mjsheng.myappstore.Statistics.StatisticsInfo;
import com.mjsheng.myappstore.activity.AppStoreActivity;
import com.mjsheng.myappstore.bean.AppDateInfo;
import com.mjsheng.myappstore.bean.AppDownloadInfo;
import com.mjsheng.myappstore.comm.CommonDatas;
import com.mjsheng.myappstore.download.StorageUtils;
import com.mjsheng.myappstore.utils.ApkUtils;
import com.mjsheng.myappstore.utils.Configure;
import com.mjsheng.myappstore.utils.MySQLData;
import com.mjsheng.myappstore.utils.Utils;
import com.mjsheng.myappstore.utils.update.ToastTool;
import com.tianma.netdetector.lib.NetStateChangeReceiver;

import org.json.JSONArray;
import org.json.JSONObject;
import org.lzh.framework.updatepluginlib.UpdateConfig;
import org.lzh.framework.updatepluginlib.base.UpdateParser;
import org.lzh.framework.updatepluginlib.model.CheckEntity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;

import cn.jpush.android.api.JPushInterface;
import okhttp3.Call;
import okhttp3.Response;
import uk.co.chrisjenx.calligraphy.CalligraphyConfig;

/**
 * Created by Administrator on 2016/2/17 0017.
 */

public class MyApplication extends MultiDexApplication implements Thread.UncaughtExceptionHandler {
    public static String userName = null;
    private static final String TAG = "--MyApplication--";
    public static Context context;
    public static boolean LOOP_STOPING = false; //停止 循环
    public static AppStoreActivity mainActivity;
    public static int ageType = 1;
    private static int mSelectTimeLong = 10;
    private static MyApplication instance;
    private Date mStartTime;
    private Date mEndTime;
    private Calendar mCurrentCalendar = null;
    private SimpleDateFormat mDateFormat = null;
    private static List<Activity> activityList = new LinkedList();

    public static Context getAppContext() {
        return context;
    }

    // 单例模式中获取唯一的ExitApplication实例
    public static MyApplication getInstance() {
        if (null == instance) {
            instance = new MyApplication();
        }
        return instance;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        Configuration config = getResources().getConfiguration();
        int smallestScreenWidthDp = config.smallestScreenWidthDp;
        Log.e("mjsheng", "smallestScreenWidthDp=" + smallestScreenWidthDp);

        //by mjsheng 激活
        MySQLData.SetData(this, CommonDatas.SP_USER_VIP, "1");

        CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
                //                .setDefaultFontPath("fonts/1234.ttf")
                //                .setDefaultFontPath("fonts/Roboto-RobotoRegular.ttf")
                .setFontAttrId(R.attr.fontPath)
                .build()
        );


        // 设置开启日志,发布时请关闭日志
        JPushInterface.setDebugMode(true);
        JPushInterface.requestPermission(this);
        // 初始化 JPush
        JPushInterface.init(this);

        context = getApplicationContext();
        Thread.setDefaultUncaughtExceptionHandler(this);
        mDateFormat = new SimpleDateFormat("HH:mm");
        initOKHttp();

        //初始化升级框架
        ToastTool.init(context);
        initUpdatePulgin(context);

        Aria.init(this);
        Aria.get(this).getDownloadConfig().setMaxTaskNum(1);


        NetStateChangeReceiver.registerReceiver(this);
    }

    private boolean finished = false;

    public boolean isFinished() {
        return finished;
    }

    public void setFinished(boolean b) {
        this.finished = b;
    }

    private void initOKHttp() {
        //必须调用初始化
        OkGo.init(this);
        //以下都不是必须的，根据需要自行选择,一般来说只需要 debug,缓存相关,cookie相关的 就可以了
        OkGo.getInstance()
                // 打开该调试开关,打印级别INFO,并不是异常,是为了显眼,不需要就不要加入该行
                // 最后的true表示是否打印okgo的内部异常，一般打开方便调试错误
                .debug("OkGo", Level.INFO, true)
                //如果使用默认的 60秒,以下三行也不需要传
//                .setConnectTimeout(3000)  //全局的连接超时时间
//                .setReadTimeOut(3000)     //全局的读取超时时间
//                .setWriteTimeOut(3000)    //全局的写入超时时间
                //可以全局统一设置缓存模式,默认是不使用缓存,可以不传,具体其他模式看 github 介绍 https://github.com/jeasonlzy/
                .setCacheMode(CacheMode.REQUEST_FAILED_READ_CACHE)
                //可以全局统一设置缓存时间,默认永不过期,具体使用方法看 github 介绍
                .setCacheTime(CacheEntity.CACHE_NEVER_EXPIRE)
                //可以全局统一设置超时重连次数,默认为三次,那么最差的情况会请求4次(一次原始请求,三次重连请求),不需要可以设置为0
                .setRetryCount(4)
                .setCookieStore(new PersistentCookieStore())        //cookie持久化存储，如果cookie不过期，则一直有效
                //可以设置https的证书,以下几种方案根据需要自己设置 方法一：信任所有证书,不安全有风险
                .setCertificates();

        com.lzy.okserver.download.DownloadManager downloadManager = DownloadService.getDownloadManager();
//        downloadManager.setTargetFolder(StorageUtils.getFileRoot(this));
        downloadManager.setTargetFolder(PathUtils.getExternalDownloadsPath() + "/ygj/");
        downloadManager.getThreadPool().setCorePoolSize(5);
    }

    private void initUpdatePulgin(Context context) {
        CheckEntity checkEntity = new CheckEntity();
        checkEntity.setMethod("POST");
        checkEntity.setUrl(CommonDatas.UPDATE_URL);
        Map<String, String> params = new HashMap<>();
        params.put("package_name", CommonDatas.UPDATE_PKG);
        params.put("key", Configure.HTTP_KEY);
        checkEntity.setParams(params);
        UpdateConfig.getConfig()
                .setCheckEntity(checkEntity)
                .setUpdateParser(new UpdateParser() {
                    @Override
                    public org.lzh.framework.updatepluginlib.model.Update parse(String response) throws Exception {
                        //                        Log.e("mjsehng", "下载嘻嘻嘻嘻嘻"+response);
                        org.lzh.framework.updatepluginlib.model.Update update = new org.lzh.framework.updatepluginlib.model.Update();
                        try {
                            JSONObject object = new JSONObject(response);
                            Integer code = object.optInt("code");
                            if (code == 200) {
                                JSONObject jsonObject = object.getJSONObject("data");
                                // 此apk包的下载地址
                                update.setUpdateUrl(jsonObject.optString("url"));
                                // 此apk包的版本号
                                update.setVersionCode(jsonObject.optInt("version_code"));
                                // 此apk包的版本名称
                                update.setVersionName(jsonObject.optString("version_name"));
                                // 此apk包的更新内容
                                update.setUpdateContent(jsonObject.optString("desc"));
                                //强制更新内容
                                if (jsonObject.optString("forced_update").equals("1")) {
                                    update.setForced(true);
                                } else {
                                    update.setForced(false);
                                }

                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        return update;
                    }
                });

    }

    // 添加Activity到容器中
    public static void addActivity(Activity activity) {
        activityList.add(activity);
    }

    // 遍历所有Activity并finish
    public void exit() {
        for (Activity activity : activityList) {
            activity.finish();
        }
    }

    public static void sendAppUsedTime(String random, String type) {
        StatisticsInfo statisticsInfo = null;
        if (type.equals("0")) {
            statisticsInfo = new StatisticsInfo(getAppContext());
        } else if (type.equals("1")) {
            statisticsInfo = new StatisticsInfo(getAppContext(), StatisticsInfo.WEEK);
        }
        List<AppInformation> list = null;
        List<AppInformation> localAppList = new ArrayList<>();

        if (statisticsInfo != null) {
            list = statisticsInfo.getShowList();
            if (list != null && list.size() > 0) {
                for (AppInformation appInformation : list) {
                    if (!Utils.isSystemApp(getAppContext(), appInformation.getPackageName())) {
                        localAppList.add(appInformation);
                    }
                }
            } else Log.e("fht", "今日没有打开的应用");
        } else Log.e("fht", "获取信息失败");

        JSONObject data = new JSONObject();
        JSONArray appinfo = new JSONArray();
        try {
            if (localAppList.size() > 0) {
                for (int i = 0; i < 5; i++) {
                    AppInformation information = localAppList.get(i);
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("package", information.getPackageName());
                    jsonObject.put("use_time", (int) information.getUsedTimebyDay() / 1000);
                    appinfo.put(jsonObject);
                }
                data.put("data", appinfo);
            }
        } catch (Exception e) {
            Log.e("fht", e.getMessage());
        }
        OkGo.post(Configure.SEND_USEDTIME)
                .params("sn", Utils.getSerial())
                .params("random", random)
                .params("data", data.toString())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        com.alibaba.fastjson.JSONObject object = JSON.parseObject(s);
                        int code = object.getInteger("code");
                        String msg = object.getString("msg");
                        Log.e("fht", "code:" + code + "," + msg);
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        Log.e("fht", e.getMessage());
                    }
                });

    }


    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        Log.e(TAG, ex.getMessage(), new Exception(ex));
        Utils.showToast(this, "程序出现异常，即将退出。。。");
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Intent i = getBaseContext().getPackageManager()
                .getLaunchIntentForPackage(getBaseContext().getPackageName());
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(i);
        //退出程序
        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(1);

    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        // 取消BroadcastReceiver注册
        NetStateChangeReceiver.unregisterReceiver(this);
    }



}
