package com.mayi.fastdevelop.base;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;

import com.mayi.fastdevelop.util.ActivitysManager;
import com.mayi.fastdevelop.util.DateUtil;
import com.mayi.fastdevelop.util.FileUtil;
import com.mayi.fastdevelop.util.LogUtils;
import com.mayi.fastdevelop.util.WriteHandler;
import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.CsvFormatStrategy;
import com.orhanobut.logger.DiskLogAdapter;
import com.orhanobut.logger.DiskLogStrategy;
import com.orhanobut.logger.Logger;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreater;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreater;
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.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.tencent.bugly.crashreport.CrashReport;
import com.tencent.smtt.sdk.CookieManager;
import com.tencent.smtt.sdk.CookieSyncManager;
import com.tencent.smtt.sdk.QbSdk;
import com.tencent.smtt.sdk.WebStorage;

import java.text.SimpleDateFormat;
import java.util.Date;

public abstract class BaseApplication extends Application {

    private static BaseApplication mInstance;
    private int logSize = 5 * 1024 * 1024;//默认记录Log文件大小--5M
    // 全局Activity 个数
    private int mActivityNum = 0;
    private boolean mBackground = false;

    @Override
    public void onCreate() {
        mInstance = this;
        super.onCreate();
        registerActivityListener();
        initLog();
        initX5Webview();
        initSmartRefreshLayout();
    }

    private void initSmartRefreshLayout() {
        SmartRefreshLayout.setDefaultRefreshHeaderCreater(new DefaultRefreshHeaderCreater() {
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
                layout.setPrimaryColorsId(android.R.color.black, android.R.color.white);//全局设置主题颜色
                layout.setReboundDuration(75);
                return new ClassicsHeader(context)
                        .setSpinnerStyle(SpinnerStyle.Translate)
                        .setFinishDuration(75);//指定为经典Header，默认是 贝塞尔雷达Header
            }
        });
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreater(new DefaultRefreshFooterCreater() {
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                layout.setReboundDuration(75);
                //指定为经典Footer，默认是 BallPulseFooter
                return new ClassicsFooter(context).setSpinnerStyle(SpinnerStyle.Translate).setFinishDuration(75);
            }
        });
    }

    /**
     * 全局Activity 生命周期监听
     */
    private void registerActivityListener() {
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                // 监听到 Activity创建事件 将该 Activity 加入list
                ActivitysManager.addActivity(activity);
            }

            @Override
            public void onActivityStarted(Activity activity) {
                if (mActivityNum == 0 && mBackground) {
                    mBackground = false;
                }
                mActivityNum++;
            }

            @Override
            public void onActivityResumed(Activity activity) {
            }

            @Override
            public void onActivityPaused(Activity activity) {
            }

            @Override
            public void onActivityStopped(Activity activity) {
                mActivityNum--;
                if (mActivityNum == 0) {
                    mBackground = true;
                }
            }

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

            @Override
            public void onActivityDestroyed(Activity activity) {
                // 监听到 Activity销毁事件 将该Activity 从list中移除
                ActivitysManager.finishActivity(activity);
            }
        });
    }

    public void initBugly(String key, boolean isDebug) {
        CrashReport.initCrashReport(getApplicationContext(), key, isDebug);
    }

    private void initX5Webview() {
        //清空所有Cookie
        CookieSyncManager.createInstance(getApplicationContext());
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.removeSessionCookies(null);
        cookieManager.removeAllCookie();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            cookieManager.flush();
        } else {
            CookieSyncManager.getInstance().sync();
        }
        WebStorage.getInstance().deleteAllData();

        //搜集本地tbs内核信息并上报服务器，服务器返回结果决定使用哪个内核。
        QbSdk.PreInitCallback cb = new QbSdk.PreInitCallback() {

            @Override
            public void onViewInitFinished(boolean arg0) {
                //x5內核初始化完成的回调，为true表示x5内核加载成功，否则表示x5内核加载失败，会自动切换到系统内核。
                LogUtils.i("X5内核加载完成:" + arg0);
            }

            @Override
            public void onCoreInitFinished() {
            }
        };
        //x5内核初始化接口
        QbSdk.initX5Environment(getApplicationContext(), cb);
    }

    /**
     * 设置日志文件大小
     *
     * @param logSize
     */
    public void setLogSize(int logSize) {
        this.logSize = logSize;
    }

    private void initLog() {
        LogUtils.TAG = getPackageName();
        if (isWriteLog()) {
            String diskPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + getPackageName() + "/logger/";
            String folder = diskPath + DateUtil.getCurrentDate();
            HandlerThread ht = new HandlerThread("AndroidFileLogger." + folder);
            ht.start();
            Handler handler = new WriteHandler(ht.getLooper(), folder, logSize);
            DiskLogStrategy logStrategy = new DiskLogStrategy(handler);
            Logger.addLogAdapter(new DiskLogAdapter(CsvFormatStrategy.newBuilder().tag(getPackageName()).logStrategy(logStrategy).build()));
            //删除3天前的日志文件
            int logSaveDay = getLogSaveDay();
            if (logSaveDay < 1) {
                logSaveDay = 3;
            }
            for (int i = 0; i < 10; i++) {
                Date date = new Date(System.currentTimeMillis() - (logSaveDay + i) * 24 * 60 * 60 * 1000);
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                String time = format.format(date);
                FileUtil.deleteFile(diskPath + time);
            }
        }
        Logger.addLogAdapter(new AndroidLogAdapter() {
            @Override
            public boolean isLoggable(int priority, String tag) {
                return isShowLog();
            }
        });
    }

    public static BaseApplication getInstance() {
        return mInstance;
    }

    /**
     * 继承BasicApplication后，实现该方法，返回自定义的子类AppContext.this即可，不要返回父类BasicApplication对象
     */
    public abstract Application getChildApplication();

    /**
     * 是否显示log
     *
     * @return
     */
    public abstract boolean isShowLog();

    /**
     * 是否需要记录日志到本地，默认开启
     *
     * @return
     */
    public boolean isWriteLog() {
        return true;
    }

    /**
     * 获取日志保留时间不能小于1，默认保留3天
     *
     * @return
     */
    public int getLogSaveDay() {
        return 3;
    }

    public boolean isBackground() {
        return mBackground;
    }
}
