package com.ironsource.mediationsdk;

import android.content.Context;
import android.os.SystemClock;
import android.text.TextUtils;
import com.ironsource.bb;
import com.ironsource.environment.thread.IronSourceThreadManager;
import com.ironsource.gr;
import com.ironsource.j5;
import com.ironsource.l5;
import com.ironsource.l9;
import com.ironsource.mediationsdk.IronSource;
import com.ironsource.mediationsdk.d;
import com.ironsource.mediationsdk.logger.IronLog;
import com.ironsource.mediationsdk.logger.IronSourceLogger;
import com.ironsource.mediationsdk.logger.IronSourceLoggerManager;
import com.ironsource.mediationsdk.utils.IronSourceAES;
import com.ironsource.mediationsdk.utils.IronSourceUtils;
import com.ironsource.p4;
import com.mbridge.msdk.newreward.function.common.MBridgeCommon;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import org.json.JSONException;
import org.json.JSONObject;
/* loaded from: classes4.dex */
public class e {

    /* renamed from: a  reason: collision with root package name */
    private final String f2635a = "1";
    private final String b = MBridgeCommon.DYNAMIC_VIEW_TEMPLATE_VALUE;
    private final String c = MBridgeCommon.DYNAMIC_VIEW_TEMPLATE_VALUE;
    private final String d = "GenericNotifications";
    private f e;
    private IronSource.AD_UNIT f;
    private l5 g;
    private p4 h;
    private ISBannerSize i;

    /* loaded from: classes4.dex */
    public static class a implements Runnable {

        /* renamed from: a  reason: collision with root package name */
        protected WeakReference<p4> f2636a;
        protected d.a b;
        protected int c;
        protected String d;
        protected long e;
        protected int f;
        private int h;
        private final URL k;
        private final JSONObject l;
        private final boolean m;
        private final int n;
        private final long o;
        private final boolean p;
        private final boolean q;
        protected String g = "other";
        protected String i = "";
        protected int j = 0;

        public a(p4 p4Var, URL url, JSONObject jSONObject, boolean z, int i, long j, boolean z2, boolean z3, int i2) {
            this.f2636a = new WeakReference<>(p4Var);
            this.k = url;
            this.l = jSONObject;
            this.m = z;
            this.n = i;
            this.o = j;
            this.p = z2;
            this.q = z3;
            this.h = i2;
        }

        private String a() {
            return this.h == 2 ? bb.b().d() : bb.b().c();
        }

        private String a(HttpURLConnection httpURLConnection) throws IOException {
            InputStreamReader inputStreamReader = new InputStreamReader(httpURLConnection.getInputStream());
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            StringBuilder sb = new StringBuilder();
            while (true) {
                String readLine = bufferedReader.readLine();
                if (readLine == null) {
                    bufferedReader.close();
                    inputStreamReader.close();
                    return sb.toString();
                }
                sb.append(readLine);
            }
        }

        private HttpURLConnection a(URL url, long j) throws IOException {
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            httpURLConnection.setReadTimeout((int) j);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setDoOutput(true);
            return httpURLConnection;
        }

        private JSONObject a(String str, String str2) throws JSONException {
            String decode = IronSourceAES.decode(str, str2);
            if (TextUtils.isEmpty(decode)) {
                throw new JSONException("decryption error");
            }
            return new JSONObject(decode);
        }

        private void a(long j, long j2) {
            long time = j - (new Date().getTime() - j2);
            if (time > 0) {
                SystemClock.sleep(time);
            }
        }

        /* JADX WARN: Removed duplicated region for block: B:11:0x0057  */
        /* JADX WARN: Removed duplicated region for block: B:12:0x0063  */
        /* JADX WARN: Removed duplicated region for block: B:15:0x006b  */
        /* JADX WARN: Removed duplicated region for block: B:16:0x0076  */
        /*
            Code decompiled incorrectly, please refer to instructions dump.
            To view partially-correct add '--show-bad-code' argument
        */
        private void a(java.net.HttpURLConnection r8, org.json.JSONObject r9, boolean r10) throws java.lang.Exception {
            /*
                r7 = this;
                java.io.OutputStream r8 = r8.getOutputStream()
                java.io.OutputStreamWriter r0 = new java.io.OutputStreamWriter
                java.lang.String r1 = "UTF-8"
                r0.<init>(r8, r1)
                java.io.BufferedWriter r1 = new java.io.BufferedWriter
                r1.<init>(r0)
                int r2 = r7.h
                r3 = 2
                if (r2 != r3) goto L4b
                com.ironsource.bb r2 = com.ironsource.bb.b()     // Catch: org.json.JSONException -> L1e
                java.lang.String r2 = r2.a()     // Catch: org.json.JSONException -> L1e
                goto L4d
            L1e:
                r2 = move-exception
                com.ironsource.l9 r4 = com.ironsource.l9.d()
                r4.a(r2)
                java.lang.String r4 = r2.getLocalizedMessage()
                r7.i = r4
                r4 = 1015(0x3f7, float:1.422E-42)
                r7.j = r4
                r4 = 1
                r7.h = r4
                com.ironsource.mediationsdk.logger.IronLog r4 = com.ironsource.mediationsdk.logger.IronLog.INTERNAL
                java.lang.StringBuilder r5 = new java.lang.StringBuilder
                java.lang.String r6 = "get encrypted session key exception "
                r5.<init>(r6)
                java.lang.String r2 = r2.getMessage()
                java.lang.StringBuilder r2 = r5.append(r2)
                java.lang.String r2 = r2.toString()
                r4.error(r2)
            L4b:
                java.lang.String r2 = ""
            L4d:
                java.lang.String r9 = r9.toString()
                java.lang.String r4 = r7.a()
                if (r10 == 0) goto L63
                com.ironsource.mediationsdk.logger.IronLog r10 = com.ironsource.mediationsdk.logger.IronLog.INTERNAL
                java.lang.String r5 = "compressing and encrypting auction request"
                r10.verbose(r5)
                java.lang.String r9 = com.ironsource.mediationsdk.utils.IronSourceAES.compressAndEncrypt(r4, r9)
                goto L67
            L63:
                java.lang.String r9 = com.ironsource.mediationsdk.utils.IronSourceAES.encode(r4, r9)
            L67:
                int r10 = r7.h
                if (r10 != r3) goto L76
                java.lang.Object[] r9 = new java.lang.Object[]{r2, r9}
                java.lang.String r10 = "{\"sk\" : \"%1$s\", \"ct\" : \"%2$s\"}"
                java.lang.String r9 = java.lang.String.format(r10, r9)
                goto L80
            L76:
                java.lang.Object[] r9 = new java.lang.Object[]{r9}
                java.lang.String r10 = "{\"request\" : \"%1$s\"}"
                java.lang.String r9 = java.lang.String.format(r10, r9)
            L80:
                r1.write(r9)
                r1.flush()
                r1.close()
                r0.close()
                r8.close()
                return
            */
            throw new UnsupportedOperationException("Method not decompiled: com.ironsource.mediationsdk.e.a.a(java.net.HttpURLConnection, org.json.JSONObject, boolean):void");
        }

        private JSONObject b(String str, String str2) throws JSONException {
            IronLog.INTERNAL.verbose("decrypting and decompressing auction response");
            String decryptAndDecompress = IronSourceAES.decryptAndDecompress(str, str2);
            if (decryptAndDecompress != null) {
                return new JSONObject(decryptAndDecompress);
            }
            throw new JSONException("decompression error");
        }

        protected JSONObject a(JSONObject jSONObject, boolean z) throws JSONException {
            String a2 = a();
            String string = jSONObject.getString(this.h == 2 ? "ct" : gr.n);
            return z ? b(a2, string) : a(a2, string);
        }

        protected void a(String str, boolean z, boolean z2) throws JSONException {
            if (TextUtils.isEmpty(str)) {
                throw new JSONException("empty response");
            }
            JSONObject jSONObject = new JSONObject(str);
            if (z) {
                jSONObject = a(jSONObject, z2);
            }
            d.a a2 = d.b().a(jSONObject);
            this.b = a2;
            this.c = a2.c();
            this.d = this.b.d();
        }

        protected void a(boolean z, p4 p4Var, long j) {
            if (z) {
                p4Var.a(this.b.h(), this.b.a(), this.b.e(), this.b.f(), this.b.b(), this.f + 1, j, this.j, this.i);
            } else {
                p4Var.a(this.c, this.d, this.f + 1, this.g, j);
            }
        }

        protected boolean b() {
            long time;
            int responseCode;
            String str;
            this.e = new Date().getTime();
            try {
                this.h = this.j == 1015 ? 1 : this.h;
                this.f = 0;
                HttpURLConnection httpURLConnection = null;
                while (true) {
                    int i = this.f;
                    int i2 = this.n;
                    if (i >= i2) {
                        this.f = i2 - 1;
                        this.g = "trials_fail";
                        return false;
                    }
                    try {
                        time = new Date().getTime();
                        String str2 = "Auction Handler: auction trial " + (this.f + 1) + " out of " + this.n + " max trials";
                        IronSourceLoggerManager.getLogger().log(IronSourceLogger.IronSourceTag.INTERNAL, str2, 0);
                        IronSourceUtils.sendAutomationLog(str2);
                        httpURLConnection = a(this.k, this.o);
                        a(httpURLConnection, this.l, this.p);
                        responseCode = httpURLConnection.getResponseCode();
                    } catch (SocketTimeoutException e) {
                        l9.d().a(e);
                        if (httpURLConnection != null) {
                            httpURLConnection.disconnect();
                        }
                        this.c = 1006;
                        this.d = "Connection timed out";
                        IronLog.INTERNAL.error("Auction socket timeout exception " + e.getMessage());
                    } catch (Throwable th) {
                        l9.d().a(th);
                        IronLog.INTERNAL.error("getting exception " + th);
                        if (httpURLConnection != null) {
                            httpURLConnection.disconnect();
                        }
                        this.c = 1000;
                        this.d = th.getMessage();
                        this.g = "other";
                        return false;
                    }
                    if (responseCode == 200 || responseCode == 204) {
                        break;
                    }
                    this.c = 1001;
                    String str3 = "Auction response code not valid, error code response from server - " + responseCode;
                    this.d = str3;
                    IronLog.INTERNAL.error(str3);
                    httpURLConnection.disconnect();
                    if (this.f < this.n - 1) {
                        a(this.o, time);
                    }
                    this.f++;
                }
                try {
                    a(a(httpURLConnection), this.m, this.q);
                    httpURLConnection.disconnect();
                    return true;
                } catch (JSONException e2) {
                    l9.d().a(e2);
                    if (e2.getMessage() != null && e2.getMessage().equalsIgnoreCase("decryption error")) {
                        this.c = 1003;
                        str = "Auction decryption error";
                    } else if (e2.getMessage() == null || !e2.getMessage().equalsIgnoreCase("decompression error")) {
                        this.c = 1002;
                        str = "Auction parsing error";
                    } else {
                        this.c = 1008;
                        str = "Auction decompression error";
                    }
                    this.d = str;
                    this.g = "parsing";
                    IronLog.INTERNAL.error("Auction handle response exception " + e2.getMessage());
                    httpURLConnection.disconnect();
                    return false;
                }
            } catch (Exception e3) {
                l9.d().a(e3);
                this.c = 1007;
                this.d = e3.getMessage();
                this.f = 0;
                this.g = "other";
                IronLog.INTERNAL.error("Auction request exception " + e3.getMessage());
                return false;
            }
        }

        @Override // java.lang.Runnable
        public void run() {
            boolean b = b();
            p4 p4Var = this.f2636a.get();
            if (p4Var == null) {
                return;
            }
            a(b, p4Var, new Date().getTime() - this.e);
        }
    }

    @Deprecated
    public e(IronSource.AD_UNIT ad_unit, l5 l5Var, p4 p4Var) {
        this.f = ad_unit;
        this.g = l5Var;
        this.h = p4Var;
    }

    public e(f fVar) {
        this.e = fVar;
    }

    private JSONObject a(Map<String, Object> map, List<String> list, h hVar, int i, boolean z, IronSourceSegment ironSourceSegment) throws JSONException {
        i iVar = new i(this.f);
        iVar.a(map);
        iVar.a(list);
        iVar.a(hVar);
        iVar.a(i);
        iVar.a(this.i);
        iVar.a(ironSourceSegment);
        iVar.b(z);
        return d.b().a(iVar);
    }

    public void a(Context context, i iVar, p4 p4Var) {
        try {
            IronSourceThreadManager.INSTANCE.postMediationBackgroundTask(this.e.a(context, iVar, p4Var));
        } catch (Exception e) {
            l9.d().a(e);
            IronLog.INTERNAL.error("execute auction exception " + e.getMessage());
            if (p4Var != null) {
                p4Var.a(1000, e.getMessage(), 0, "other", 0L);
            }
        }
    }

    @Deprecated
    public void a(Context context, Map<String, Object> map, List<String> list, h hVar, int i, IronSourceSegment ironSourceSegment) {
        try {
            boolean isEncryptedResponse = IronSourceUtils.isEncryptedResponse();
            IronSourceThreadManager.INSTANCE.postMediationBackgroundTask(new a(this.h, new URL(this.g.a(false)), a(map, list, hVar, i, isEncryptedResponse, ironSourceSegment), isEncryptedResponse, this.g.g(), this.g.m(), this.g.n(), this.g.o(), this.g.d()));
        } catch (Exception e) {
            l9.d().a(e);
            IronLog.INTERNAL.error("execute auction exception " + e.getMessage());
            this.h.a(1000, e.getMessage(), 0, "other", 0L);
        }
    }

    @Deprecated
    public void a(Context context, Map<String, Object> map, List<String> list, h hVar, int i, IronSourceSegment ironSourceSegment, ISBannerSize iSBannerSize) {
        this.i = iSBannerSize;
        a(context, map, list, hVar, i, ironSourceSegment);
    }

    public void a(j5 j5Var, int i, j5 j5Var2) {
        for (String str : j5Var.h()) {
            d.b().a("reportLoadSuccess", j5Var.c(), d.b().a(str, i, j5Var, "", "", ""));
        }
        if (j5Var2 != null) {
            for (String str2 : j5Var2.h()) {
                d.b().a("reportLoadSuccess", "GenericNotifications", d.b().a(str2, i, j5Var, "", MBridgeCommon.DYNAMIC_VIEW_TEMPLATE_VALUE, ""));
            }
        }
    }

    public void a(j5 j5Var, int i, j5 j5Var2, String str) {
        for (String str2 : j5Var.b()) {
            d.b().a("reportImpression", j5Var.c(), d.b().a(str2, i, j5Var, "", "", str));
        }
        if (j5Var2 != null) {
            for (String str3 : j5Var2.b()) {
                d.b().a("reportImpression", "GenericNotifications", d.b().a(str3, i, j5Var, "", MBridgeCommon.DYNAMIC_VIEW_TEMPLATE_VALUE, str));
            }
        }
    }

    public void a(ArrayList<String> arrayList, ConcurrentHashMap<String, j5> concurrentHashMap, int i, j5 j5Var, j5 j5Var2) {
        int j = j5Var2.j();
        Iterator<String> it = arrayList.iterator();
        while (it.hasNext()) {
            String next = it.next();
            if (!next.equals(j5Var2.c())) {
                j5 j5Var3 = concurrentHashMap.get(next);
                int j2 = j5Var3.j();
                String i2 = j5Var3.i();
                String str = j2 < j ? "1" : MBridgeCommon.DYNAMIC_VIEW_TEMPLATE_VALUE;
                IronLog.INTERNAL.verbose("instance=" + j5Var3.c() + ", instancePriceOrder= " + j2 + ", loseReasonCode=" + str + ", winnerInstance=" + j5Var2.c() + ", winnerInstancePriceOrder=" + j);
                for (String str2 : j5Var3.g()) {
                    d.b().a("reportAuctionLose", j5Var3.c(), d.b().a(str2, i, j5Var2, i2, str, ""));
                }
            }
        }
        if (j5Var != null) {
            for (String str3 : j5Var.g()) {
                d.b().a("reportAuctionLose", "GenericNotifications", d.b().a(str3, i, j5Var2, "", MBridgeCommon.DYNAMIC_VIEW_TEMPLATE_VALUE, ""));
            }
        }
    }

    public void a(CopyOnWriteArrayList<y> copyOnWriteArrayList, ConcurrentHashMap<String, j5> concurrentHashMap, int i, j5 j5Var, j5 j5Var2) {
        ArrayList<String> arrayList = new ArrayList<>();
        Iterator<y> it = copyOnWriteArrayList.iterator();
        while (it.hasNext()) {
            arrayList.add(it.next().c());
        }
        a(arrayList, concurrentHashMap, i, j5Var, j5Var2);
    }

    public boolean a() {
        return this.e.a();
    }
}
