package a.c.b.z.g;

import a.c.b.h;
import a.c.b.i;
import a.c.b.k;
import a.c.b.l;
import a.c.b.s;
import a.c.b.z.b;
import a.c.b.z.c;
import a.c.b.z.e;
import a.c.b.z.f;
import android.text.TextUtils;
import java.io.Closeable;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

public class e extends c {
    private static final int A = 4;
    private static final String B = "SocketChannel";
    private static final long C = 100;
    private static final int D = 100;
    public static final String t = "TcpNoDelay";
    public static final String u = "ReuseAddress";
    public static final String v = "SoLingerMode";
    public static final String w = "Linger";
    public static final String x = "TrafficClass";
    public static final int y = 192;
    private static final String z = "\\.";
    private volatile boolean h;
    private ServerSocket i;
    private Socket j;
    private f.a k;
    private a.c.b.b0.a l;
    private ExecutorService m;
    private ExecutorService n;
    private f o;
    private int p;
    private volatile boolean q;
    private boolean r;
    private final Object s;

    public class a implements c<Boolean> {

        /* renamed from: a  reason: collision with root package name */
        public final /* synthetic */ a.c.b.z.e f91a;

        public a(a.c.b.z.e eVar) {
            this.f91a = eVar;
        }

        @Override // a.c.b.z.c
        public Boolean a(s sVar) {
            return Boolean.valueOf(sVar != null);
        }

        public void a(Boolean bool) {
            a.c.b.z.e eVar = this.f91a;
            if (eVar != null) {
                eVar.a(Boolean.valueOf(bool != null));
            }
        }

        @Override // a.c.b.z.c
        public void a(Exception exc) {
            a.c.b.z.e eVar = this.f91a;
            if (eVar != null) {
                eVar.a(exc);
            }
        }
    }

    public e(b bVar) {
        this(bVar, false);
    }

    public e(b bVar, boolean z2) {
        this(bVar, z2, true);
    }

    public e(b bVar, boolean z2, boolean z3) {
        super(bVar, z2);
        this.h = false;
        this.p = 100;
        this.q = false;
        this.r = false;
        this.s = new Object();
        if (z3) {
            this.l = new a.c.b.b0.a();
        }
    }

    /* access modifiers changed from: private */
    public /* synthetic */ Boolean a(String str, int i2, Map map) throws Exception {
        a.c.b.a0.c a2 = k.a();
        try {
            ServerSocket serverSocket = new ServerSocket();
            this.i = serverSocket;
            serverSocket.setReuseAddress(true);
            this.i.bind(a(str, i2));
            j();
            a2.a(B, a() + " server channel bind at " + m());
            try {
                Socket accept = this.i.accept();
                this.j = accept;
                accept.setKeepAlive(true);
                a(map);
                a2.a(B, a() + " accept an client channel: " + this.j.getRemoteSocketAddress());
                synchronized (this.s) {
                    if (!this.q) {
                        u();
                        b(true);
                        t();
                        a2.a(B, a() + " server channel connect success!");
                        h();
                        l();
                        return Boolean.TRUE;
                    }
                    return Boolean.FALSE;
                }
            } catch (IOException e) {
                k();
                throw new a.c.b.z.a(a() + " server channel accept error.", e);
            }
        } catch (Exception e2) {
            String str2 = a() + " server channel start fail: " + e2.getMessage();
            a2.b(B, str2, e2);
            close();
            throw new a.c.b.z.a(str2, e2);
        }
    }

    /* access modifiers changed from: private */
    public /* synthetic */ Boolean a(Map map, String str, int i2) throws Exception {
        a.c.b.a0.c a2 = k.a();
        for (int i3 = 1; i3 <= this.p; i3++) {
            try {
                Socket socket = new Socket();
                this.j = socket;
                socket.setKeepAlive(true);
                a(map);
                this.j.connect(a(str, i2), 100);
                synchronized (this.s) {
                    if (!this.q) {
                        u();
                        b(true);
                        t();
                        a2.a(B, a() + " client channel connect success!");
                        h();
                        return Boolean.TRUE;
                    }
                    return Boolean.FALSE;
                }
            } catch (IOException e) {
                String str2 = a() + " channel connect error " + m() + ": " + e.getMessage() + ", try times: " + i3;
                synchronized (this.s) {
                    if (this.q) {
                        a2.b(B, str2 + ", socket closed", e);
                        return Boolean.FALSE;
                    }
                    a(this.j);
                    if (i3 < this.p) {
                        if (i3 % 10 == 0) {
                            a2.d(B, str2 + ", will try again.");
                        }
                        Thread.sleep(C);
                    } else {
                        a2.b(B, str2, e);
                        a(e);
                    }
                }
            }
        }
        throw new a.c.b.z.a(a() + " channel connect fail after " + this.p + " times");
    }

    /* access modifiers changed from: private */
    public /* synthetic */ Thread a(Runnable runnable) {
        Thread thread = new Thread(runnable, a("R"));
        thread.setDaemon(true);
        return thread;
    }

    private static InetSocketAddress a(String str, int i2) throws UnknownHostException {
        String[] split = str.split(z);
        if (split.length == 4) {
            byte[] bArr = new byte[4];
            for (int i3 = 0; i3 < 4; i3++) {
                if (TextUtils.isDigitsOnly(split[i3])) {
                    bArr[i3] = (byte) (Integer.parseInt(split[i3]) & 255);
                } else {
                    throw new UnknownHostException("invalid ip address");
                }
            }
            return new InetSocketAddress(InetAddress.getByAddress(bArr), i2);
        }
        throw new UnknownHostException("ip address is of illegal length");
    }

    private Future<Boolean> a(s sVar, long j2, a.c.b.z.e eVar) {
        return a(sVar.a(i.SEND_SYNC), j2, new a(eVar));
    }

    /* access modifiers changed from: private */
    public static /* synthetic */ void a(a.c.b.a0.c cVar, s sVar, Exception exc) {
        cVar.b(B, "send ack fail:" + sVar.a(), exc);
    }

    /* access modifiers changed from: private */
    public /* synthetic */ void a(s sVar, d dVar, long j2) {
        int m2 = sVar.m();
        try {
            b.b().a(dVar);
            if (!a(sVar, (a.c.b.z.e) null).get(j2, TimeUnit.MILLISECONDS).booleanValue()) {
                b.b().a(m2);
                dVar.a(new a.c.b.z.a("Send request fail: " + m2));
            }
        } catch (Exception e) {
            b.b().a(m2);
            dVar.a(e);
        }
    }

    private void a(Closeable closeable) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (Exception e) {
                k.a().e(B, "close quietly:" + e.getMessage());
            }
        }
    }

    private void a(Map<String, Integer> map) throws IOException {
        if (this.j != null && map != null) {
            k.a().a(B, " set Socket Extra Options!");
            boolean z2 = true;
            if (map.containsKey(t)) {
                this.j.setTcpNoDelay(map.get(t).intValue() != 0);
            }
            if (map.containsKey(u)) {
                this.j.setReuseAddress(map.get(u).intValue() != 0);
            }
            if (map.containsKey(v) && map.containsKey(w)) {
                Socket socket = this.j;
                if (map.get(v).intValue() == 0) {
                    z2 = false;
                }
                socket.setSoLinger(z2, map.get(w).intValue());
            }
            if (map.containsKey(x)) {
                this.j.setTrafficClass(map.get(x).intValue());
            }
        }
    }

    /* JADX INFO: finally extract failed */
    /* access modifiers changed from: private */
    public /* synthetic */ Boolean b(s sVar, a.c.b.z.e eVar) throws Exception {
        try {
            OutputStream outputStream = this.j.getOutputStream();
            if (q()) {
                s s2 = s.s();
                h a2 = s2.g().a(sVar.g());
                ByteBuffer b = this.l.b(sVar.c());
                a2.d(b.remaining() + 20);
                byte[] k2 = a2.k();
                s2.t();
                outputStream.write(k2);
                outputStream.write(b.array(), 0, b.remaining());
            } else {
                outputStream.write(sVar.g().k());
                outputStream.write(sVar.n(), sVar.c().arrayOffset(), sVar.e());
            }
            outputStream.flush();
            if (eVar != null) {
                eVar.a(Boolean.TRUE);
            }
            Boolean bool = Boolean.TRUE;
            sVar.t();
            return bool;
        } catch (Exception e) {
            k.a().b(B, "Send message error: \n" + sVar.a(), e);
            if (eVar != null) {
                eVar.a(e);
            }
            sVar.t();
            return Boolean.FALSE;
        } catch (Throwable th) {
            sVar.t();
            throw th;
        }
    }

    /* access modifiers changed from: private */
    public /* synthetic */ Thread b(Runnable runnable) {
        Thread thread = new Thread(runnable, a("W"));
        thread.setDaemon(true);
        return thread;
    }

    private Future<Boolean> b(int i2, String str, Map<String, Integer> map) {
        synchronized (this.s) {
            i();
            this.q = false;
        }
        FutureTask futureTask = new FutureTask(new Callable(map, str, i2) {
            /* class a.c.b.z.g.$$Lambda$e$DgyYyYHUYFtTlBC2b38LrAWi3k */
            public final /* synthetic */ Map f$1;
            public final /* synthetic */ String f$2;
            public final /* synthetic */ int f$3;

            {
                this.f$1 = r2;
                this.f$2 = r3;
                this.f$3 = r4;
            }

            @Override // java.util.concurrent.Callable
            public final Object call() {
                return e.this.a(this.f$1, this.f$2, this.f$3);
            }
        });
        Thread thread = new Thread(futureTask, a("C"));
        thread.setDaemon(true);
        thread.start();
        return futureTask;
    }

    private void b(boolean z2) {
        this.h = z2;
    }

    private Future<Boolean> c(int i2, String str, Map<String, Integer> map) {
        synchronized (this.s) {
            i();
            this.q = false;
        }
        FutureTask futureTask = new FutureTask(new Callable(str, i2, map) {
            /* class a.c.b.z.g.$$Lambda$e$bHANQ8Gz9Kp46vo2HmAB9xijPCM */
            public final /* synthetic */ String f$1;
            public final /* synthetic */ int f$2;
            public final /* synthetic */ Map f$3;

            {
                this.f$1 = r2;
                this.f$2 = r3;
                this.f$3 = r4;
            }

            @Override // java.util.concurrent.Callable
            public final Object call() {
                return e.this.a(this.f$1, this.f$2, this.f$3);
            }
        });
        Thread thread = new Thread(futureTask, a("A"));
        thread.setDaemon(true);
        thread.start();
        return futureTask;
    }

    private void l() {
        k.a().a(B, "Wait more client connection.");
        Thread thread = new Thread(new Runnable() {
            /* class a.c.b.z.g.$$Lambda$e$v4Tggc3OxZEug4uhYwXJ_9xdzA8 */

            public final void run() {
                e.this.r();
            }
        });
        thread.setDaemon(true);
        thread.setName(a("M"));
        thread.start();
    }

    private String m() {
        return c() + ":" + f();
    }

    private void n() throws IOException {
        synchronized (this.s) {
            this.q = true;
            ExecutorService executorService = this.n;
            if (executorService != null) {
                executorService.shutdown();
                this.n = null;
            }
            ExecutorService executorService2 = this.m;
            if (executorService2 != null) {
                executorService2.shutdown();
                this.m = null;
            }
        }
        a((Closeable) this.o);
        a(this.j);
        a(this.i);
        b(false);
    }

    /* access modifiers changed from: private */
    public /* synthetic */ void r() {
        a.c.b.a0.c a2 = k.a();
        while (!this.i.isClosed()) {
            try {
                Socket accept = this.i.accept();
                if (b()) {
                    a2.b(B, "ATTENTION: Found unknown connection from:" + accept.getRemoteSocketAddress());
                    accept.close();
                } else {
                    try {
                        a2.a(B, a() + " channel accept another client: " + this.j.getRemoteSocketAddress());
                        a(this.j);
                        this.j = accept;
                        accept.setKeepAlive(true);
                        this.j.setTcpNoDelay(true);
                        synchronized (this.s) {
                            if (!this.q) {
                                b(true);
                                t();
                                a2.a(B, a() + " server channel reconnect success!");
                                h();
                            }
                        }
                    } catch (IOException e) {
                        a2.b(B, "connect more connect error: " + e.getMessage(), e);
                        a(this.j);
                        b(false);
                    }
                }
            } catch (Exception e2) {
                a2.b(B, "accept more connection error: " + e2.getMessage(), e2);
                return;
            }
        }
    }

    /* access modifiers changed from: private */
    public /* synthetic */ void s() {
        this.o.run();
        b(false);
    }

    private void t() {
        a((Closeable) this.o);
        this.o = new f(this);
        this.n.submit(new Runnable() {
            /* class a.c.b.z.g.$$Lambda$e$p9CpdwHG2w3WVxxwNtldK0Hs3I */

            public final void run() {
                e.this.s();
            }
        });
    }

    private void u() {
        this.n = Executors.newSingleThreadExecutor(new ThreadFactory() {
            /* class a.c.b.z.g.$$Lambda$e$pjikdgEkGwA8akWhqUdRnMsPog */

            public final Thread newThread(Runnable runnable) {
                return e.this.a(runnable);
            }
        });
        this.m = Executors.newSingleThreadExecutor(new ThreadFactory() {
            /* class a.c.b.z.g.$$Lambda$e$dzY_g68WFdHzRE07s36mhIW4f0 */

            public final Thread newThread(Runnable runnable) {
                return e.this.b(runnable);
            }
        });
    }

    public Future<Boolean> a(int i2, String str) throws IOException {
        if (g() == b.CUSTOM) {
            a(i2);
        }
        c(str);
        return e();
    }

    public Future<Boolean> a(int i2, String str, Map<String, Integer> map) throws IOException {
        if (g() == b.CUSTOM) {
            a(i2);
        }
        c(str);
        if (d()) {
            k.a().a(B, a() + " server channel starting: " + m());
            return c(f(), c(), map);
        }
        k.a().a(B, a() + " client channel starting: " + m());
        return b(f(), c(), map);
    }

    @Override // a.c.b.z.f
    public final <T> Future<T> a(s sVar, long j2, c<T> cVar) {
        if (j2 <= 0) {
            j2 = Long.MAX_VALUE;
        }
        if (sVar == null) {
            d dVar = new d(cVar, 0);
            dVar.a(new l("Can not send a null message"));
            return dVar;
        }
        d dVar2 = new d(cVar, j2, sVar.m());
        k.b().submit(new Runnable(sVar, dVar2, j2) {
            /* class a.c.b.z.g.$$Lambda$e$ovVRfOe4hcJ1NmGP9BEeBFQ3FOA */
            public final /* synthetic */ s f$1;
            public final /* synthetic */ d f$2;
            public final /* synthetic */ long f$3;

            {
                this.f$1 = r2;
                this.f$2 = r3;
                this.f$3 = r4;
            }

            public final void run() {
                e.this.a((e) this.f$1, (s) this.f$2, (d) this.f$3);
            }
        });
        return dVar2;
    }

    public final <T> Future<T> a(s sVar, c<T> cVar) {
        return a(sVar, 3000, cVar);
    }

    @Override // a.c.b.z.f
    public Future<Boolean> a(s sVar, a.c.b.z.e eVar) {
        return a(sVar, eVar, false, -1);
    }

    /* JADX WARNING: Code restructure failed: missing block: B:18:0x0035, code lost:
        r2 = a() + " channel not ready";
        a.c.b.k.a().b(a.c.b.z.g.e.B, r2);
     */
    /* JADX WARNING: Code restructure failed: missing block: B:19:0x0055, code lost:
        if (r3 == null) goto L_0x005f;
     */
    /* JADX WARNING: Code restructure failed: missing block: B:20:0x0057, code lost:
        r3.a((java.lang.Exception) new a.c.b.z.a(r2));
     */
    /* JADX WARNING: Code restructure failed: missing block: B:21:0x005f, code lost:
        r5.complete(r4);
     */
    /* JADX WARNING: Code restructure failed: missing block: B:22:0x0062, code lost:
        return r5;
     */
    public Future<Boolean> a(s sVar, a.c.b.z.e eVar, boolean z2, long j2) {
        if (z2) {
            return a(sVar, j2, eVar);
        }
        Boolean bool = Boolean.FALSE;
        CompletableFuture completedFuture = CompletableFuture.completedFuture(bool);
        if (sVar == null) {
            completedFuture.completeExceptionally(new l("Can not send a null message"));
            return completedFuture;
        }
        synchronized (this.s) {
            ExecutorService executorService = this.m;
            if (executorService != null && !executorService.isShutdown()) {
                return this.m.submit(new Callable(sVar, eVar) {
                    /* class a.c.b.z.g.$$Lambda$e$pI4TojAY809Asx9U5gGQnLJMPlM */
                    public final /* synthetic */ s f$1;
                    public final /* synthetic */ e f$2;

                    {
                        this.f$1 = r2;
                        this.f$2 = r3;
                    }

                    @Override // java.util.concurrent.Callable
                    public final Object call() {
                        return e.this.b(this.f$1, this.f$2);
                    }
                });
            }
        }
    }

    @Override // a.c.b.z.f
    public void a(s sVar) {
        boolean z2;
        a.c.b.a0.c a2 = k.a();
        f.a aVar = this.k;
        if (aVar != null) {
            try {
                aVar.a(sVar);
            } catch (Exception e) {
                z2 = false;
                a2.b(B, a() + ": handle message " + sVar.m() + " error.", e);
            }
        }
        z2 = true;
        if (s.a(sVar) && z2) {
            a(s.a(sVar.m()), (a.c.b.z.e) new a.c.b.z.e(sVar) {
                /* class a.c.b.z.g.$$Lambda$e$m7v2iMUtR1VR4V5NfOHXmkiw */
                public final /* synthetic */ s f$1;

                {
                    this.f$1 = r2;
                }

                @Override // a.c.b.z.c
                public final void a(Exception exc) {
                    e.a(a.c.b.a0.c.this, this.f$1, exc);
                }
            });
        }
    }

    public void a(f.a aVar) {
        if (b()) {
            k.a().d(B, "Set message handler after channel connected may loss message!");
        }
        this.k = aVar;
    }

    @Override // a.c.b.z.f
    public void a(Throwable th) {
    }

    @Override // a.c.b.z.f
    public void a(boolean z2) {
    }

    public final Future<s> b(s sVar) {
        return a(sVar, a.a());
    }

    public void b(int i2) {
        this.p = i2;
    }

    @Override // a.c.b.z.f
    public final boolean b() {
        Socket socket;
        return this.h && (socket = this.j) != null && socket.isConnected();
    }

    public void c(boolean z2) {
        this.r = z2;
    }

    @Override // java.io.Closeable, java.lang.AutoCloseable
    public final void close() throws IOException {
        n();
        k.a().a(B, a() + (d() ? " server" : " client") + " disconnect.");
        a(d());
    }

    @Override // a.c.b.z.f
    public Future<Boolean> e() throws IOException {
        if (d()) {
            k.a().a(B, a() + " server channel starting: " + m());
            return c(f(), c(), null);
        }
        k.a().a(B, a() + " client channel starting: " + m());
        return b(f(), c(), null);
    }

    @Override // a.c.b.z.g.c, a.c.b.z.f
    public int f() {
        int i2;
        ServerSocket serverSocket;
        int i3 = this.c;
        if (i3 != 0) {
            return i3;
        }
        if (g() != b.CUSTOM) {
            i2 = g().a();
        } else if (!d() || (serverSocket = this.i) == null || serverSocket.isClosed()) {
            Socket socket = this.j;
            if (socket != null && socket.isConnected()) {
                InetSocketAddress inetSocketAddress = (InetSocketAddress) this.j.getRemoteSocketAddress();
                if (inetSocketAddress != null) {
                    i2 = inetSocketAddress.getPort();
                } else {
                    k.a().b(B, "InetSocketAddress is invalid");
                    return -1;
                }
            }
            return this.c;
        } else {
            i2 = this.i.getLocalPort();
        }
        this.c = i2;
        return this.c;
    }

    @Override // a.c.b.z.f
    public void h() {
    }

    @Override // a.c.b.z.g.c, a.c.b.z.f
    public void i() {
        try {
            n();
        } catch (IOException e) {
            k.a().a(B, "Close error: " + e.getMessage(), e);
        }
    }

    @Override // a.c.b.z.g.c
    public void j() {
    }

    @Override // a.c.b.z.g.c
    public void k() {
    }

    public Socket o() {
        return this.j;
    }

    public a.c.b.b0.a p() {
        return this.l;
    }

    public boolean q() {
        return p() != null;
    }

    public boolean v() {
        return this.r;
    }
}
