package com.bjzc.bhzhgd.utils;



import android.app.Activity;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.text.TextUtils;
import android.util.Log;

;
import com.bjzc.bhzhgd.R;
import com.bjzc.bhzhgd.contans.Contans;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.download.DownloadQueue;
import com.yolanda.nohttp.rest.Request;
import com.yolanda.nohttp.rest.RequestQueue;

import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.CertificateFactory;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;

/**
 * Nohttp工具类
 */
public class NoProgresshttpUtils {

    private static NoProgresshttpUtils sUtils;
    private RequestQueue mQueue;

    /**
     * 下载队列.
     */
    private static DownloadQueue downloadQueue;

    private NoProgresshttpUtils() {
        mQueue = NoHttp.newRequestQueue(8);
    }

    /**
     * DCL单例模式  双层锁
     *
     * @return
     */
    public static NoProgresshttpUtils getInstance() {
        if (sUtils == null) {
            synchronized (NohttpUtils.class) {
                if (sUtils == null) {
                    sUtils = new NoProgresshttpUtils();
                }
            }
        }
        return sUtils;
    }

    /**
     * 下载队列.
     */
    public static DownloadQueue getDownloadInstance() {
        if (downloadQueue == null)
            downloadQueue = NoHttp.newDownloadQueue(1);
        return downloadQueue;
    }


    public <T> void add(Activity mActivity, int what, Request<T> request, HttpListener<T> callback) {
        String tokenTemp = (String) SPUtils.get(mActivity, Contans.LOGIN_TOKEN, "");
        if(!TextUtils.isEmpty(tokenTemp)){
            String token = RSAUtils.decryptBASE64StrLocal(tokenTemp);;
            String credential = "Bearer " + token;
            request.addHeader("Authorization", credential);
            showLog(request.url(),mActivity);
//            if(!TextUtils.isEmpty(token)){
//                showLog(credential);
//                showLog(new Gson().toJson(request.headers()));
//            }
        }
        mQueue.add(what, request, new HttpResponseListenerNoProgress<T>(request, callback));
    }

    public void showLog(String logText,Context context) {
        if (isApkInDebug(context)) {
            if(TextUtils.isEmpty(logText)){
                Log.i("app", "logText is null");
            }else{
                Log.i("app", logText);
            }
        }
    }

    /**
     * 判断当前应用是否是debug状态
     */

    public static boolean isApkInDebug(Context context) {
        try {
            ApplicationInfo info = context.getApplicationInfo();
            return (info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 取消这个sign这个标记的所有请求
     *
     * @param sign
     */
    public void cancelBySign(Object sign) {
        mQueue.cancelBySign(sign);
    }

    /**
     * 取消队列中所有请求
     */
    public void cancelAll() {
        mQueue.cancelAll();
    }

    /**
     * 退出App停止所有请求
     */
    public void stopAll() {
        mQueue.stop();
    }

    public static SSLSocketFactory getSSLSocketFactory(Context context){
        try {
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(null);
            String certificateAlias = Integer.toString(0);
            keyStore.setCertificateEntry(certificateAlias, certificateFactory.
                    generateCertificate(context.getResources().openRawResource(R.raw.ca1)));
            SSLContext sslContext = SSLContext.getInstance("TLS");
            final TrustManagerFactory trustManagerFactory =
                    TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init(keyStore);
            sslContext.init
                    (
                            null,
                            trustManagerFactory.getTrustManagers(),
                            new SecureRandom()
                    );
            return sslContext.getSocketFactory();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }
}