package com.uiui.zyappstore.base;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import androidx.annotation.NonNull;

import com.alibaba.sdk.android.push.CloudPushService;
import com.alibaba.sdk.android.push.CommonCallback;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.arialyy.aria.core.Aria;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreator;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.tencent.android.tpush.XGIOperateCallback;
import com.tencent.android.tpush.XGPushConfig;
import com.tencent.android.tpush.XGPushManager;
import com.tencent.mmkv.MMKV;
import com.uiui.zyappstore.R;
import com.uiui.zyappstore.manager.ConnectManager;
import com.uiui.zyappstore.network.NetInterfaceManager;
import com.uiui.zyappstore.push.PushManager;
import com.uiui.zyappstore.receiver.AppManagerReceiver;
import com.uiui.zyappstore.utils.JGYUtils;
import com.uiui.zyappstore.utils.LogUtils;
import com.uiui.zyappstore.utils.ToastUtil;
import com.uiui.zyappstore.utils.Utils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by asus on 2017/10/27.
 */
public class BaseApplication extends Application {
    private static final String TAG = BaseApplication.class.getSimpleName();

    static {
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
            @NonNull
            @Override
            public RefreshHeader createRefreshHeader(@NonNull Context context, @NonNull RefreshLayout layout) {
                layout.setPrimaryColorsId(R.color.download, R.color.default_text_color);//全局设置主题颜色
                return new ClassicsHeader(context);//.setTimeFormat(new DynamicTimeFormat("更新于 %s"));//指定为经典Header，默认是 贝塞尔雷达Header
            }
        });
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                //指定为经典Footer，默认是 BallPulseFooter
                return new ClassicsFooter(context).setDrawableSize(20);
            }
        });
    }

    @Override
    public void onCreate() {
        super.onCreate();
        String rootDir = MMKV.initialize(this);
        Log.i(TAG, "mmkv root: " + rootDir);

        JGYUtils.init(this);
        PushManager.init(this);
        tPushInit();
        aliyunPushInit();
        ToastUtil.init(this);
        ConnectManager.init(this);
        Aria.init(this);
        Aria.get(this).getDownloadConfig().setMaxTaskNum(1);
        Aria.get(this).getDownloadConfig().setConvertSpeed(true);

        if (!isDebug(this)) {
            catchException();
        }
        registAppReceive();
        NetInterfaceManager.init(this);
        JGYUtils.hookWebView();

        //全局字体初始化
//        CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
//                        //                .setDefaultFontPath("fonts/1234.ttf")
//                .setDefaultFontPath("fonts/SourceHanSansCN-ExtraLight.ttf")
////                        .setDefaultFontPath("fonts/test.ttf")
//                        .setFontAttrId(R.attr.fontPath)
//                        .build()
//        );
    }

    private void tPushInit() {
        XGPushConfig.enableDebug(this, true);
        XGPushManager.registerPush(this, new XGIOperateCallback() {
            @Override
            public void onSuccess(Object data, int flag) {
                //token在设备卸载重装的时候有可能会变
                Log.e("TPush", "注册成功，设备token为：" + data);
                List<XGPushManager.AccountInfo> accountInfoList = new ArrayList<>();
                accountInfoList.add(new XGPushManager.AccountInfo(XGPushManager.AccountType.CUSTOM.getValue(), Utils.getSerial()));
                XGPushManager.upsertAccounts(getApplicationContext(), accountInfoList, new XGIOperateCallback() {
                    @Override
                    public void onSuccess(Object data, int flag) {
                        Log.e("TPush", "onSuccess, data:" + data + ", flag:" + flag);
                    }

                    @Override
                    public void onFail(Object data, int errCode, String msg) {
                        Log.e("TPush", "onFail, data:" + data + ", code:" + errCode + ", msg:" + msg);
                    }
                });
            }

            @Override
            public void onFail(Object data, int errCode, String msg) {
                Log.e("TPush", "注册失败，错误码：" + errCode + ",错误信息：" + msg);
            }
        });
    }

    private void aliyunPushInit() {
        PushServiceFactory.init(this);
        final CloudPushService pushService = PushServiceFactory.getCloudPushService();
        pushService.setLogLevel(CloudPushService.LOG_DEBUG);
        pushService.register(this, new CommonCallback() {
            @Override
            public void onSuccess(String response) {
                Log.e("AliyunPush", "init cloudchannel success");
                Log.e("AliyunPush", "init cloudchannel success  " + pushService.getDeviceId());
            }

            @Override
            public void onFailed(String errorCode, String errorMessage) {
                Log.e("AliyunPush", "init cloudchannel failed -- errorcode:" + errorCode + " -- errorMessage:" + errorMessage);
            }
        });
        String account = Utils.getSerial();
        pushService.bindAccount(account, new CommonCallback() {
            @Override
            public void onSuccess(String s) {
                Log.e("AliyunPush", "bind account " + account + " success\n");
            }

            @Override
            public void onFailed(String errorCode, String errorMsg) {
                Log.e("AliyunPush", "bind account " + account + " failed." +
                        "errorCode: " + errorCode + ", errorMsg:" + errorMsg);
            }
        });
        String alias = Utils.getSerial();
        pushService.addAlias(account, new CommonCallback() {
            @Override
            public void onSuccess(String s) {
                Log.e("AliyunPush", "add alias " + alias + " success\n");
            }

            @Override
            public void onFailed(String errorCode, String errorMsg) {
                Log.e("AliyunPush", "add alias " + alias + " failed." +
                        "errorCode: " + errorCode + ", errorMsg:" + errorMsg + "\n");
            }
        });
    }


    private AppManagerReceiver mAppManagerReceiver;

    private void registAppReceive() {
        mAppManagerReceiver = new AppManagerReceiver();
        IntentFilter filter = new IntentFilter();
        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        filter.addAction(Intent.ACTION_PACKAGE_ADDED);
        filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
        filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
        filter.addDataScheme("package");
        registerReceiver(mAppManagerReceiver, filter);
    }

    public boolean isDebug(Context context) {
        boolean isDebug = context.getApplicationInfo() != null &&
                (context.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
        return isDebug;
    }

    private void catchException() {
        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
                                                      @Override
                                                      public void uncaughtException(@NonNull Thread t, @NonNull Throwable e) {
                                                          LogUtils.d("捕获异常子线程:", Thread.currentThread().getName() +
                                                                  "在:" + e.getStackTrace()[0].getClassName());
                                                      }
                                                  }
        );
        //下面是新增方法!
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Looper.loop(); //会先执行这个方法,然后在执行下面的异常捕获方法!
                    } catch (Exception e) {
                        LogUtils.d("捕获异常主线程:", Thread.currentThread().getName() + "在:" + e.getStackTrace()[0].getClassName());
                        e.printStackTrace();
                    }
                }
            }
        });
    }
}
