package ai.guiji.duix.sample.network;

import android.content.Context;
import android.util.Log;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.StringRequest;

import org.json.JSONException;
import org.json.JSONObject;


import ai.guiji.duix.sample.Constant;


public class TokenRequest extends BaseRequest {

    public TokenRequest(Context context, RequestQueue queue, INetworkCallback callback) {
        super(context, queue, callback);
    }

    public void getSig(String appId) {
        int requestId = Constant.API_REQUEST_ID.GET_SIG.ordinal();
        StringRequest jsonObjectRequest = new StringRequest(String.format(Constant.API_GET_SIG, appId), response -> {
            Log.e(TAG, "getSig: " + response);
            if (callback != null) {
                try {
                    JSONObject json = new JSONObject(response);
                    boolean success = json.getBoolean("success");
                    String message = json.optString("message");
                    if (success) {
                        String data = json.getString("data");
                        onResult(requestId, data);
                    } else {
                        onResultError(requestId, message);
                    }
                } catch (JSONException e) {
                    onJsonParseError(requestId);
                }
            }
        }, new VolleyRequestError(requestId));
        mQueue.add(jsonObjectRequest);
    }


    public void checkSig(String sig) {
        int requestId = Constant.API_REQUEST_ID.CHECK_SIG.ordinal();
        StringRequest jsonObjectRequest = new StringRequest(String.format(Constant.API_CHECK_SIG, sig), response -> {
            Log.e(TAG, "checkSig: " + response);
            if (callback != null) {
                try {
                    JSONObject json = new JSONObject(response);
                    boolean success = json.getBoolean("success");
                    String message = json.optString("msg");
                    if (success) {
                        JSONObject data = json.getJSONObject("data");
                        String token = data.getString("token");
                        onResult(requestId, token);
                    } else {
                        onResultError(requestId, message);
                    }
                } catch (JSONException e) {
                    onJsonParseError(requestId);
                }
            }
        }, new VolleyRequestError(requestId));
        mQueue.add(jsonObjectRequest);
    }
}
