package com.autotech.we1l.volley;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.toolbox.StringRequest;
import com.autotech.we1l.app.MyApp;

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

import java.util.Map;

public class VolleyRequest {

    private static final int MY_VOLLEY_TIME_OUT = 0;
    private static VolleyRequest volleyRequest;

    private static final int RESULT_SUCCESS = 1, RESULT_FAILED = 0;

    private VolleyRequest() {
    }

    public static synchronized VolleyRequest getInstance() {
        try {
            if (volleyRequest == null)
                return volleyRequest = new VolleyRequest();
            else
                return volleyRequest;
        } catch (Exception e) {
            throw new IllegalArgumentException();
        }
    }

    public Request<String> post(String URL, Map<String, String> map, IVolleyRequest iVolleyRequest) {

        if (URL.isEmpty()) return null;

        StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, response -> {
            try {
                iVolleyRequest.getResponse(new JSONObject(response), null, RESULT_SUCCESS);
                iVolleyRequest.onSuccess(new JSONObject(response));
            } catch (JSONException e) {
                iVolleyRequest.getResponse(null, "", RESULT_FAILED);
                iVolleyRequest.onFail(null);
            }

        }, error -> {
            iVolleyRequest.getResponse(null, error.getMessage(), RESULT_FAILED);
            iVolleyRequest.onFail(error);
        }) {
            protected Map<String, String> getParams() {
                return map;
            }
        };

        stringRequest.setRetryPolicy(new DefaultRetryPolicy(
                MY_VOLLEY_TIME_OUT,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        stringRequest.setShouldCache(false);

        MyApp.getInstance().addToRequestQueue(stringRequest);

        return stringRequest;
    }

}
