package com.parse;

import com.parse.ParseRequest;
import com.parse.http.ParseHttpBody;
import com.parse.http.ParseHttpRequest;
import com.parse.http.ParseHttpResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONStringer;
import p137.C2742;
import p138.p139.p143.p144.C2803;
import p138.p176.p177.p242.p246.p251.C4303;

/* JADX INFO: loaded from: classes.dex */
public class ParseRESTCommand extends ParseRequest<JSONObject> {
    public static URL server;
    public String httpPath;
    public String installationId;
    public final JSONObject jsonParameters;
    public String localId;
    public String masterKey;
    public final String sessionToken;

    public static abstract class Init<T extends Init<T>> {
        public String httpPath;
        public String installationId;
        public JSONObject jsonParameters;
        public String localId;
        public String masterKey;
        public ParseHttpRequest.Method method = ParseHttpRequest.Method.GET;
        public String sessionToken;
    }

    public ParseRESTCommand(Init<?> init) {
        super(init.method, createUrl(init.httpPath));
        this.sessionToken = init.sessionToken;
        this.installationId = init.installationId;
        this.masterKey = init.masterKey;
        this.httpPath = init.httpPath;
        this.jsonParameters = init.jsonParameters;
        this.localId = init.localId;
    }

    public ParseRESTCommand(String str, ParseHttpRequest.Method method, Map<String, ?> map, String str2) {
        this(str, method, map != null ? (JSONObject) NoObjectsEncoder.INSTANCE.encode(map) : null, str2);
    }

    public ParseRESTCommand(String str, ParseHttpRequest.Method method, JSONObject jSONObject, String str2) {
        super(method, createUrl(str));
        this.httpPath = str;
        this.jsonParameters = jSONObject;
        this.localId = null;
        this.sessionToken = str2;
    }

    public ParseRESTCommand(String str, ParseHttpRequest.Method method, JSONObject jSONObject, String str2, String str3) {
        super(method, createUrl(str));
        this.httpPath = str;
        this.jsonParameters = jSONObject;
        this.localId = str2;
        this.sessionToken = str3;
    }

    public static void addToStringer(JSONStringer jSONStringer, Object obj) throws JSONException {
        if (!(obj instanceof JSONObject)) {
            if (!(obj instanceof JSONArray)) {
                jSONStringer.value(obj);
                return;
            }
            JSONArray jSONArray = (JSONArray) obj;
            jSONStringer.array();
            for (int i = 0; i < jSONArray.length(); i++) {
                addToStringer(jSONStringer, jSONArray.get(i));
            }
            jSONStringer.endArray();
            return;
        }
        jSONStringer.object();
        JSONObject jSONObject = (JSONObject) obj;
        Iterator<String> itKeys = jSONObject.keys();
        ArrayList<String> arrayList = new ArrayList();
        while (itKeys.hasNext()) {
            arrayList.add(itKeys.next());
        }
        Collections.sort(arrayList);
        for (String str : arrayList) {
            jSONStringer.key(str);
            addToStringer(jSONStringer, jSONObject.opt(str));
        }
        jSONStringer.endObject();
    }

    public static String createUrl(String str) {
        if (str == null) {
            return server.toString();
        }
        try {
            return new URL(server, str).toString();
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
    }

    public static ParseRESTCommand fromJSONObject(JSONObject jSONObject) {
        String strOptString = jSONObject.optString("httpPath");
        ParseHttpRequest.Method methodFromString = ParseHttpRequest.Method.fromString(jSONObject.optString("httpMethod"));
        String strOptString2 = jSONObject.optString("sessionToken", null);
        return new ParseRESTCommand(strOptString, methodFromString, jSONObject.optJSONObject("parameters"), jSONObject.optString("localId", null), strOptString2);
    }

    public static LocalIdManager getLocalIdManager() {
        return ParseCorePlugins.INSTANCE.getLocalIdManager();
    }

    public static void getLocalPointersIn(Object obj, ArrayList<JSONObject> arrayList) {
        if (obj instanceof JSONObject) {
            JSONObject jSONObject = (JSONObject) obj;
            if ("Pointer".equals(jSONObject.opt("__type")) && jSONObject.has("localId")) {
                arrayList.add(jSONObject);
                return;
            } else {
                Iterator<String> itKeys = jSONObject.keys();
                while (itKeys.hasNext()) {
                    getLocalPointersIn(jSONObject.get(itKeys.next()), arrayList);
                }
            }
        }
        if (obj instanceof JSONArray) {
            JSONArray jSONArray = (JSONArray) obj;
            for (int i = 0; i < jSONArray.length(); i++) {
                getLocalPointersIn(jSONArray.get(i), arrayList);
            }
        }
    }

    public static boolean isValidCommandJSONObject(JSONObject jSONObject) {
        return jSONObject.has("httpPath");
    }

    public void addAdditionalHeaders(ParseHttpRequest.Builder builder) {
        String str = this.installationId;
        if (str != null) {
            builder.headers.put("X-Parse-Installation-Id", str);
        }
        String str2 = this.sessionToken;
        if (str2 != null) {
            builder.headers.put("X-Parse-Session-Token", str2);
        }
        String str3 = this.masterKey;
        if (str3 != null) {
            builder.headers.put("X-Parse-Master-Key", str3);
        }
    }

    @Override // com.parse.ParseRequest
    public C2742<JSONObject> executeAsync(ParseHttpClient parseHttpClient, ProgressCallback progressCallback, ProgressCallback progressCallback2, C2742<Void> c2742) {
        try {
            ArrayList<JSONObject> arrayList = new ArrayList();
            getLocalPointersIn(this.jsonParameters, arrayList);
            for (JSONObject jSONObject : arrayList) {
                String objectId = getLocalIdManager().getObjectId((String) jSONObject.get("localId"));
                if (objectId == null) {
                    throw new IllegalStateException("Tried to serialize a command referencing a new, unsaved object.");
                }
                jSONObject.put("objectId", objectId);
                jSONObject.remove("localId");
            }
            maybeChangeServerOperation();
        } catch (JSONException unused) {
        }
        return super.executeAsync(parseHttpClient, progressCallback, progressCallback2, c2742);
    }

    public String getCacheKey() {
        String string;
        JSONObject jSONObject = this.jsonParameters;
        if (jSONObject != null) {
            try {
                JSONStringer jSONStringer = new JSONStringer();
                addToStringer(jSONStringer, jSONObject);
                string = jSONStringer.toString();
            } catch (JSONException e) {
                throw new RuntimeException(e.getMessage());
            }
        } else {
            string = "";
        }
        if (this.sessionToken != null) {
            StringBuilder sbM4889 = C2803.m4889(string);
            sbM4889.append(this.sessionToken);
            string = sbM4889.toString();
        }
        return String.format("ParseRESTCommand.%s.%s.%s", this.method.toString(), ParseDigestUtils.md5(this.httpPath), ParseDigestUtils.md5(string));
    }

    public final void maybeChangeServerOperation() {
        String objectId;
        if (this.localId == null || (objectId = getLocalIdManager().getObjectId(this.localId)) == null) {
            return;
        }
        this.localId = null;
        String str = this.httpPath + String.format("/%s", objectId);
        this.httpPath = str;
        this.url = createUrl(str);
        if (this.httpPath.startsWith("classes") && this.method == ParseHttpRequest.Method.POST) {
            this.method = ParseHttpRequest.Method.PUT;
        }
    }

    @Override // com.parse.ParseRequest
    public ParseHttpBody newBody(ProgressCallback progressCallback) {
        JSONObject jSONObject = this.jsonParameters;
        if (jSONObject == null) {
            throw new IllegalArgumentException(String.format("Trying to execute a %s command without body parameters.", this.method.toString()));
        }
        try {
            if (this.method == ParseHttpRequest.Method.GET || this.method == ParseHttpRequest.Method.DELETE) {
                jSONObject = new JSONObject(this.jsonParameters.toString());
                jSONObject.put("_method", this.method.toString());
            }
            return new ParseByteArrayHttpBody(jSONObject.toString(), "application/json");
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    @Override // com.parse.ParseRequest
    public ParseHttpRequest newRequest(ParseHttpRequest.Method method, String str, ProgressCallback progressCallback) {
        ParseHttpRequest.Builder builder = new ParseHttpRequest.Builder((this.jsonParameters == null || method == ParseHttpRequest.Method.POST || method == ParseHttpRequest.Method.PUT) ? super.newRequest(method, str, progressCallback) : super.newRequest(ParseHttpRequest.Method.POST, str, progressCallback));
        addAdditionalHeaders(builder);
        return new ParseHttpRequest(builder, null);
    }

    @Override // com.parse.ParseRequest
    public C2742<JSONObject> onResponseAsync(ParseHttpResponse parseHttpResponse, ProgressCallback progressCallback) {
        InputStream inputStream = null;
        try {
            try {
                inputStream = parseHttpResponse.content;
                String str = new String(C4303.toByteArray(inputStream));
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException unused) {
                    }
                }
                int i = parseHttpResponse.statusCode;
                if (i < 200 || i >= 600) {
                    ParseRequest.ParseRequestException parseRequestException = new ParseRequest.ParseRequestException(-1, str);
                    parseRequestException.isPermanentFailure = true;
                    return C2742.m4804((Exception) parseRequestException);
                }
                try {
                    JSONObject jSONObject = new JSONObject(str);
                    if (i >= 400 && i < 500) {
                        ParseRequest.ParseRequestException parseRequestException2 = new ParseRequest.ParseRequestException(jSONObject.optInt("code"), jSONObject.optString("error"));
                        parseRequestException2.isPermanentFailure = true;
                        return C2742.m4804((Exception) parseRequestException2);
                    }
                    if (i < 500) {
                        return C2742.m4805(jSONObject);
                    }
                    ParseRequest.ParseRequestException parseRequestException3 = new ParseRequest.ParseRequestException(jSONObject.optInt("code"), jSONObject.optString("error"));
                    parseRequestException3.isPermanentFailure = false;
                    return C2742.m4804((Exception) parseRequestException3);
                } catch (JSONException e) {
                    return C2742.m4804((Exception) newTemporaryException("bad json response", e));
                }
            } catch (IOException e2) {
                C2742<JSONObject> c2742M4804 = C2742.m4804((Exception) e2);
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException unused2) {
                    }
                }
                return c2742M4804;
            }
        } catch (Throwable th) {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException unused3) {
                }
            }
            throw th;
        }
    }

    public void releaseLocalIds() {
        if (this.localId != null) {
            getLocalIdManager().releaseLocalIdOnDisk(this.localId);
        }
        try {
            ArrayList arrayList = new ArrayList();
            getLocalPointersIn(this.jsonParameters, arrayList);
            Iterator it = arrayList.iterator();
            while (it.hasNext()) {
                getLocalIdManager().releaseLocalIdOnDisk((String) ((JSONObject) it.next()).get("localId"));
            }
        } catch (JSONException unused) {
        }
    }
}
