package com.itant.shiwushu.tool;

import android.text.TextUtils;

import com.itant.shiwushu.constant.ResultCode;
import com.itant.shiwushu.manager.UserManager;

import java.io.IOException;

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

/**
 * Created by Jason on 2018/8/30.
 */

public class RequestClient {
    private OkHttpClient interceptOkHttpClient;
    private OkHttpClient normalOkHttpClient;
    private static RequestClient client;

    private RequestClient() {
        interceptOkHttpClient = new OkHttpClient();
    }

    public static RequestClient getClient() {
        if (client == null) {
            init();
        }

        return client;
    }

    private static synchronized void init() {
        if (client == null) {
            client = new RequestClient();
        }
    }

    public OkHttpClient getInterceptOkHttpClient() {
        if (interceptOkHttpClient == null) {
            Interceptor networkInterceptor = new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request request = chain.request();
                    //---------请求之前进行请求过滤-----
                    Response response = new Response.Builder().code(ResultCode.FAILED_NEED_RE_LOGIN).build();
                    if (UserManager.getInstance().getUser() == null ||
                            TextUtils.isEmpty(UserManager.getInstance().getUser().getUserId()) ||
                            TextUtils.isEmpty(UserManager.getInstance().getUser().getToken())) {
                        return response;
                    }

                    response = chain.proceed(request);
                    return response;
                }
            };
            interceptOkHttpClient = new OkHttpClient.Builder()
                    .addNetworkInterceptor(networkInterceptor)
                    .build();
        }
        return interceptOkHttpClient;
    }

    public OkHttpClient getNormalOkHttpClient() {
        if (normalOkHttpClient == null) {
            normalOkHttpClient = new OkHttpClient.Builder().build();
        }
        return normalOkHttpClient;
    }
}
