package com.taikor.investment;

import android.app.Application;

import com.taikor.investment.mylibrary.TAnalytics;
import com.taikor.investment.utils.NetworkUtils;
import com.zhy.http.okhttp.OkHttpUtils;

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

import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MyApplication extends Application {

    private static MyApplication myApplication;
    private HashMap<String, Object> mMap;
    public boolean networkOnLine;

    @Override
    public void onCreate() {
        super.onCreate();
        setupHttpCache();
        TAnalytics.init(this);
    }
    
    public static MyApplication getInstance() {
        if(myApplication==null){
            myApplication=new MyApplication();
        }
        return myApplication;
    }

   //把obj对象放置暂存区
    public Object put(String key, Object obj) {
        if (mMap == null) {
            mMap = new HashMap<>();
        }
        return mMap.put(key, obj);
    }
    
    //从暂存区读取对象
    public Object get(String key) {
        if (mMap != null) {
            return mMap.remove(key);
        }
        return null;
    }

    /**
     * 设置缓存
     */
    private void setupHttpCache() {
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addNetworkInterceptor(new RewriteCacheControl())//加入拦截器
                .addInterceptor(new RewriteCacheControl())
                .connectTimeout(10000L, TimeUnit.MILLISECONDS)
                .readTimeout(10000L, TimeUnit.MILLISECONDS)
                .build();

        OkHttpUtils.initClient(okHttpClient);
    }

    /**
     * 拦截器
     */
    private class RewriteCacheControl implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            networkOnLine = NetworkUtils.isNetworkOnline(getApplicationContext());
            
            Request request = chain.request();
            if (!networkOnLine) {
                // 如果没有网络
                request = request.newBuilder()
                        .cacheControl(CacheControl.FORCE_CACHE)
                        .build();
            } else {
                //请求网络
                request = request.newBuilder()
                        .cacheControl(CacheControl.FORCE_NETWORK)
                        .build();
            }
            
            Response response = chain.proceed(request);
            if (networkOnLine) {
                int maxAge = 0; // 有网络时 设置缓存超时时间0个小时
                response.newBuilder()
                        .header("Cache-Control", "public, max-age=" + maxAge)
                        .removeHeader("Pragma")// 清除头信息，因为服务器如果不支持，会返回一些干扰信息，不清除下面无法生效
                        .build();
            } else {
                int maxStale = 60 * 60 * 24 * 28; // 无网络时，设置超时为4周
                response.newBuilder()
                        .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                        .removeHeader("Pragma")
                        .build();
            }

            return response;
        }
    }
    
}
