package com.android.chmo.http;

import android.text.TextUtils;
import android.util.Log;

import org.xutils.common.Callback;
import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.x;

/**
 * Created by Administrator on 2018/7/30.
 */

public class HttpApi {
//    public static final String BASE_URL = "http://118.190.49.85/thmodel/";

    public static final String BASE_URL = "http://118.190.49.85/thmodeltest/";


    public static String getImgUrl(String path) {
        if(TextUtils.isEmpty(path) || path.startsWith("http://")) {
            return path;
        }
        return  BASE_URL + path;
    }


    public static RequestParams getRequestParams() {
        RequestParams params = new RequestParams(BASE_URL);
        return params;
    }

    public static Callback.Cancelable POST(RequestParams params,final RequestCallback callback) {
        return request(HttpMethod.POST, params,callback);
    }


    public static Callback.Cancelable GET(RequestParams params, RequestCallback callback) {
        return request(HttpMethod.GET, params,callback);
    }



    private static Callback.Cancelable request(HttpMethod method,RequestParams params, final RequestCallback callback) {
        params.setMaxRetryCount(0);
        Callback.Cancelable cancelable = x.http().request(method, params, new Callback.CommonCallback<String>() {
            String result = null;
            boolean isError = false;

            @Override
            public void onSuccess(String result) {
                Log.i("HttpApi", "Success result : " + result);
                if (null != result){
                    this.result = result;
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e("HttpApi", "onError result : " + ex.toString());
                isError = true;
                if (null != callback) {
                    callback.onFailure("请求失败，请稍后重试");
                }
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
                // 不管成功或者失败最后都会回调该接口
                if (!isError && this.result != null) {
                    if (null != callback) {
                        callback.onSuccess(result);
                    }
                }
            }

        });

        return cancelable;
    }
}


