package com.yutou.jianr_mg;


import android.app.Activity;
import android.app.Notification;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;

import com.tencent.smtt.sdk.QbSdk;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.message.IUmengCallback;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.PushAgent;
import com.umeng.message.UmengMessageHandler;
import com.umeng.message.entity.UMessage;
import com.yutou.jianr_mg.Data.AppData;
import com.yutou.jianr_mg.Data.User;
import com.yutou.jianr_mg.Databases.UserDatabase;
import com.yutou.jianr_mg.Interfaces.HttpInterface;
import com.yutou.jianr_mg.Network.HttpApi;
import com.yutou.jianr_mg.Network.HttpUtils;
import com.yutou.jianr_mg.Tools.ActivitysManager;
import com.yutou.jianr_mg.Tools.JianRUtils;
import com.yutou.jianr_mg.Tools.Log;
import com.yutou.jianr_mg.Tools.Utils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import dalvik.system.DexClassLoader;

/**
 * Created by 58381 on 2018/1/20.
 */

public class Application extends android.app.Application {
    public static Application application;
    private static final String TAG = "Application";

    @Override
    public void onCreate() {
        super.onCreate();
        Application.application = this;
       // BlockCanary.install(this, new AppBlockCanaryContext()).start();
        System.out.println("开始初始化");

        init();
        initPlugs();
        regActivity();
        JianRUtils.initShipCardId();
        initUmeng();
        initTx();


        System.out.println("初始化结束");
    }

    private void initUmeng() {
        try {
            UMConfigure.init(this, UMConfigure.DEVICE_TYPE_PHONE, "c5ec76e4a6ebb1516359792ffee09eb5");
            MobclickAgent.setScenarioType(this, MobclickAgent.EScenarioType.E_UM_NORMAL);
            PushAgent pushAgent = PushAgent.getInstance(this);
            pushAgent.register(new IUmengRegisterCallback() {
                @Override
                public void onSuccess(String s) {
                    System.out.println("友盟推送注册成功：" + s);
                }

                @Override
                public void onFailure(String s, String s1) {
                    System.out.println("友盟推送注册失败：" + s + "(" + s1 + ")");
                }
            });
            pushAgent.setMessageHandler(new UmengMessageHandler() {
                @Override
                public Notification getNotification(Context context, UMessage uMessage) {
                    for (Map.Entry<String, String> entry : uMessage.extra.entrySet()) {
                        if (entry.getKey().equals("url")) {
                            LoadingActivity.url = entry.getValue();
                        }

                    }
                    return super.getNotification(context, uMessage);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initTx() {
        try {
            QbSdk.initX5Environment(this, new QbSdk.PreInitCallback() {
                @Override
                public void onCoreInitFinished() {
                    System.out.println("QDSDK初始化失败");
                }

                @Override
                public void onViewInitFinished(boolean b) {
                    Log.e("QDSDK", "加载内核是否成功:" + b);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void initPlugs() {
        new Thread(() -> {
            try {

                Map<String, DexClassLoader> plugsin = new HashMap<>();
                File path = new File(Application.application.getFilesDir() + "/plugin/");
                File dex = new File(Application.application.getFilesDir() + "/plugin/");
                if (!dex.exists()) {
                    dex.mkdirs();
                }
                if (path.exists()) {
                    for (File file : path.listFiles()) {
                        if (file.getName().contains(".jar")) {
                            DexClassLoader dexClassLoader = new DexClassLoader(file.getAbsolutePath(), dex.getAbsolutePath(), null, getClassLoader());
                            plugsin.put(file.getName(), dexClassLoader);
                            System.out.println("加载插件："+file.getName());
                           // AppData.plugsin.put(file.getName(), dexClassLoader);
                        }
                    }
                } else {
                    path.mkdirs();
                }
                JSONObject json = new JSONObject();
                JSONArray array = new JSONArray();
                List<String> fileName = new ArrayList<>();
                for (File file : path.listFiles()) {
                    try {
                        if (!file.getName().contains(".jar")) {
                            continue;
                        }
                        String appid = (String) plugsin.get(file.getName()).loadClass("com.yutou.jianr_mg.plugins.Data").getField("appId").get(null);
                        String md5 = Utils.getFileMD5(file);
                        System.out.println("MD5:" + md5);
                        JSONObject plugs = new JSONObject();
                        plugs.put("appid", appid);
                        plugs.put("md5", md5);
                        plugs.put("name", file.getName());
                        fileName.add(file.getName());
                        array.put(plugs);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                try {
                    json.put("array", array.toString());
                    HttpUtils.post(HttpApi.HOME_URL + HttpApi.SYSTEM_PLUGINS, json, new HttpInterface() {
                        @Override
                        public void httpGetData(String string, int code) {
                            try {
                                JSONObject json = new JSONObject(string);
                                JSONArray plugs = json.getJSONArray("data");
                                for (int i = 0; i < plugs.length(); i++) {
                                    if (fileName.contains(plugs.getString(i))) {
                                        AppData.plugsin.put(plugs.getString(i), plugsin.get(plugs.getString(i)));
                                    }
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void httpError(Exception e) {

                        }
                    });

                } catch (Exception e) {
                    e.printStackTrace();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();

    }

    private void init() {
        User user = UserDatabase.init().getUser();
        if (user == null) {
            AppData.Token = "0000";
            AppData.user = new User();
            AppData.user.setId(-1);
        } else {
            AppData.Token = user.getToken();
            AppData.user = user;
        }
        File file = new File(Utils.getAppPath());
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    private void regActivity() {
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle bundle) {
                Log.i(TAG, "创建:" + activity.getClass().getName());
                AppData.activity = activity;
                AppData.handler = new Handler(Looper.getMainLooper());
                ActivitysManager.addActivity(activity);
                PushAgent.getInstance(activity).onAppStart();
            }

            @Override
            public void onActivityStarted(Activity activity) {

            }

            @Override
            public void onActivityResumed(Activity activity) {

            }

            @Override
            public void onActivityPaused(Activity activity) {

            }

            @Override
            public void onActivityStopped(Activity activity) {

            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {

            }

            @Override
            public void onActivityDestroyed(Activity activity) {
                Log.i(TAG, "销毁:" + activity.getClass().getName());
                ActivitysManager.finishActivity(activity);
            }
        });
    }

}
