package com.wd.workoffice.app;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.Log;

import com.scwang.smartrefresh.header.BezierCircleHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.tencent.bugly.crashreport.CrashReport;
import com.wd.workoffice.R;
import com.wd.workoffice.retrofit.ApiService;
import com.wd.workoffice.retrofit.MesApiService;
import com.wd.workoffice.retrofit.RtfMesHelper;
import com.wd.workoffice.util.UserKeeper;

import java.io.IOException;
import java.util.HashMap;

import cn.jpush.android.api.JPushInterface;
import flexible.xd.android_base.base.BaseApp;
import flexible.xd.android_base.network.rtfhttp.RtfHelper;
import flexible.xd.android_base.utils.Utils;
import me.jessyan.autosize.AutoSizeConfig;
import me.jessyan.autosize.unit.Subunits;
import okhttp3.Request;
import okhttp3.Response;


/**
 * Created by flexibleXd on 2016/12/22.
 */

public class WorkApp extends BaseApp {
    private static Application instance;
    private HashMap<String, String> cookies;

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        CrashReport.initCrashReport(getApplicationContext(), "8081eafad1", Config.DEBUG);
        Utils.init(this);
        AutoSizeConfig.getInstance().setCustomFragment(true);
        AutoSizeConfig.getInstance().getUnitsManager()
                .setSupportDP(false)
                .setSupportSP(false)
                .setSupportSubunits(Subunits.MM);
        initBatNetWork();
        cookies = new HashMap<>();
        RtfMesHelper.getInstance().init(MesApiService.DOMAIN, chain -> {
            //获取请求链接
            Request originalRequest = chain.request();
            //获取url的主机地址
            String hostString = originalRequest.url().host();

            if (!cookies.containsKey(hostString)) {
                //获取磁盘里面的spCookie字符串
                String spCookie = UserKeeper.getInstance().getCookie();
                if (!TextUtils.isEmpty(spCookie)) {
                    //获取spCookie解密放到内存中
                    cookies.put(hostString, spCookie);
                }
            }

            //获取内存中的Cookie
            String memoryCookie = cookies.get(hostString);
            //拦截网络请求数据
            Request request = originalRequest.newBuilder()
                    //设置请求头Cookie值
                    .addHeader("Cookie", memoryCookie == null ? "" : memoryCookie)
                    .build();
            UserKeeper.getInstance().clearCookie();
            UserKeeper.getInstance().keepCookie(memoryCookie);
            //拦截返回数据
            Response originalResponse = chain.proceed(request);
            //判断请求头里面是否有Set-Cookie值,更新Cookie
            if (!originalResponse.headers("Set-Cookie").isEmpty()) {
                //字符串集
                StringBuilder stringBuilder = new StringBuilder();
                for (String header : originalResponse.headers("Set-Cookie")) {
                    stringBuilder.append(header);
                    stringBuilder.append(";");
                }
                //拼接Cookie成字符串
                String cookie = stringBuilder.toString();

                //更新内存中Cookies值
                cookies.put(hostString, cookie);
                //存储到本地磁盘中
                UserKeeper.getInstance().keepCookie(cookie);
                Log.e("Set-Cookie", "cookies: " + cookie + " host: " + hostString);
            }
            return originalResponse;

        });
        smartInit();
        JPushInterface.setDebugMode(true);
        JPushInterface.init(this);

    }

    private  void initBatNetWork() {
        RtfHelper.getInstance().init(ApiService.DOMAIN, chain -> {
            Request original = chain.request();
            Request request = original.newBuilder()
                    .header("Authorization", "Bearer " + UserKeeper.getInstance().getToken())
                    .header("userId", UserKeeper.getInstance().getUserId())
                    .method(original.method(), original.body())
                    .build();

            return chain.proceed(request);
        });
    }
//    private void daoInit() {
//        daoSession = DaoMaster.newDevSession(this, "workO.db");
//    }
//
//    public static DaoSession getDaoSession() {
//        return daoSession;
//    }

    private void smartInit() {
        SmartRefreshLayout.setDefaultRefreshInitializer((context, layout) -> {
            //开始设置全局的基本参数（可以被下面的DefaultRefreshHeaderCreator覆盖）
            layout.setReboundDuration(1000);
//                layout.setReboundInterpolator(new DropBounceInterpolator());
            layout.setFooterHeight(100);
            layout.setDisableContentWhenLoading(false);
            layout.setPrimaryColorsId(R.color.mainTextColor, android.R.color.white);
        });

        //全局设置默认的 Header
        SmartRefreshLayout.setDefaultRefreshHeaderCreator((context, layout) -> {
            //开始设置全局的基本参数（这里设置的属性只跟下面的MaterialHeader绑定，其他Header不会生效，能覆盖DefaultRefreshInitializer的属性和Xml设置的属性）
            return new BezierCircleHeader(context);

        });
    }

//    @Override
//    protected void attachBaseContext(Context base) {
//        super.attachBaseContext(base);
//        MultiDex.install(base);
//    }

    public static synchronized Application getApp() {
        return instance;
    }
}
