package com.hc.model.YNYD;

import android.content.Context;
import android.support.annotation.NonNull;

import com.alibaba.fastjson.JSON;
import com.hc.model.FJYD.AuthRequestBody;
import com.hc.request.FJYDConfig;
import com.hc.request.core.CallServer;
import com.hc.request.core.DefaultCallback;
import com.hc.request.core.IHttpCallback;
import com.orhanobut.logger.Logger;
import com.yanzhenjie.nohttp.Headers;
import com.yanzhenjie.nohttp.RequestMethod;
import com.yanzhenjie.nohttp.rest.StringRequest;

public class YNYDService {

    private YNYDContentProvider contentProvider;

    public YNYDService(Context context) {
        contentProvider = new YNYDContentProvider(context);
    }

    /**
     * 认证请求
     */
    public void auth(String cid, final IHttpCallback<String> callback) {
//        cid = "00000062201705271002120028799574";
        StringRequest request = getRequest(FJYDConfig.URL.AUTH);
        AuthRequestBody requestBody = new AuthRequestBody(cid);
        String body = JSON.toJSONString(requestBody);
        request.setDefineRequestBodyForJson(body);
        Logger.d("请求body %s", body);

        CallServer.getInstance().requestString(FJYDConfig.WHAT.AUTH, request, new DefaultCallback<String>() {
            @Override
            public void onStart(int what) {
                Logger.d("开始请求认证");
                if (callback != null) {
                    callback.onStart(what);
                }
            }

            @Override
            public void onSuccess(int what, @NonNull String data) {
                Logger.d("请求认证成功:" + data);
                callback.onSuccess(FJYDConfig.WHAT.AUTH, data);
            }

            @Override
            public void onFail(int what, String msg) {
                Logger.d("请求认证失败:" + msg);
                if (callback != null) {
                    callback.onFail(what, msg);
                }
            }

            @Override
            public void onError(int what, Throwable e) {
                Logger.e(e, "请求认证发生异常");
                if (callback != null) {
                    callback.onError(what, e);
                }
            }

            @Override
            public void onFinish(int what) {
                Logger.d("请求认证结束");
                if (callback != null) {
                    callback.onFinish(what);
                }
            }
        });
    }

    private StringRequest getRequest(String url) {
        StringRequest request = new StringRequest(contentProvider.getEpg() + url, RequestMethod.POST);
        request.setContentType(Headers.HEAD_VALUE_CONTENT_TYPE_JSON);
        request.addHeader(FJYDConfig.HEADS.AUTHORIZATION, contentProvider.getToken());
//        request.addHeader(FJYDConfig.HEADS.HOST, contentProvider.getEpg());
        return request;
    }
}
