// 
// Decompiled by Procyon v0.6.0
// 

package io.netty.handler.codec.http.websocketx;

import io.netty.util.concurrent.FutureListener;
import java.util.concurrent.TimeUnit;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.ssl.SslHandler;
import io.netty.channel.ChannelPipeline;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.concurrent.GenericFutureListener;
import io.netty.util.concurrent.Future;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpObject;
import io.netty.util.internal.ObjectUtil;
import io.netty.channel.ChannelPromise;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

class WebSocketServerProtocolHandshakeHandler extends ChannelInboundHandlerAdapter
{
    private final WebSocketServerProtocolConfig serverConfig;
    private ChannelHandlerContext ctx;
    private ChannelPromise handshakePromise;
    private boolean isWebSocketPath;
    
    WebSocketServerProtocolHandshakeHandler(final WebSocketServerProtocolConfig serverConfig) {
        this.serverConfig = ObjectUtil.checkNotNull(serverConfig, "serverConfig");
    }
    
    @Override
    public void handlerAdded(final ChannelHandlerContext ctx) {
        this.ctx = ctx;
        this.handshakePromise = ctx.newPromise();
    }
    
    @Override
    public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception {
        final HttpObject httpObject = (HttpObject)msg;
        if (httpObject instanceof HttpRequest) {
            final HttpRequest req = (HttpRequest)httpObject;
            if (!(this.isWebSocketPath = this.isWebSocketPath(req))) {
                ctx.fireChannelRead(msg);
                return;
            }
            try {
                final WebSocketServerHandshaker handshaker = WebSocketServerHandshakerFactory.resolveHandshaker(req, getWebSocketLocation(ctx.pipeline(), req, this.serverConfig.websocketPath()), this.serverConfig.subprotocols(), this.serverConfig.decoderConfig());
                final ChannelPromise localHandshakePromise = this.handshakePromise;
                if (handshaker == null) {
                    WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
                }
                else {
                    WebSocketServerProtocolHandler.setHandshaker(ctx.channel(), handshaker);
                    ctx.pipeline().remove(this);
                    final ChannelFuture handshakeFuture = handshaker.handshake(ctx.channel(), req);
                    handshakeFuture.addListener((GenericFutureListener<? extends Future<? super Void>>)new ChannelFutureListener() {
                        @Override
                        public void operationComplete(final ChannelFuture future) {
                            if (!future.isSuccess()) {
                                localHandshakePromise.tryFailure(future.cause());
                                ctx.fireExceptionCaught(future.cause());
                            }
                            else {
                                localHandshakePromise.trySuccess();
                                ctx.fireUserEventTriggered((Object)WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE);
                                ctx.fireUserEventTriggered((Object)new WebSocketServerProtocolHandler.HandshakeComplete(req.uri(), req.headers(), handshaker.selectedSubprotocol()));
                            }
                        }
                    });
                    this.applyHandshakeTimeout();
                }
            }
            finally {
                ReferenceCountUtil.release(req);
            }
        }
        else if (!this.isWebSocketPath) {
            ctx.fireChannelRead(msg);
        }
        else {
            ReferenceCountUtil.release(msg);
        }
    }
    
    private boolean isWebSocketPath(final HttpRequest req) {
        final String websocketPath = this.serverConfig.websocketPath();
        final String uri = req.uri();
        return this.serverConfig.checkStartsWith() ? (uri.startsWith(websocketPath) && ("/".equals(websocketPath) || this.checkNextUri(uri, websocketPath))) : uri.equals(websocketPath);
    }
    
    private boolean checkNextUri(final String uri, final String websocketPath) {
        final int len = websocketPath.length();
        if (uri.length() > len) {
            final char nextUri = uri.charAt(len);
            return nextUri == '/' || nextUri == '?';
        }
        return true;
    }
    
    private static String getWebSocketLocation(final ChannelPipeline cp, final HttpRequest req, final String path) {
        String protocol = "ws";
        if (cp.get(SslHandler.class) != null) {
            protocol = "wss";
        }
        final String host = req.headers().get(HttpHeaderNames.HOST);
        return protocol + "://" + host + path;
    }
    
    private void applyHandshakeTimeout() {
        final ChannelPromise localHandshakePromise = this.handshakePromise;
        final long handshakeTimeoutMillis = this.serverConfig.handshakeTimeoutMillis();
        if (handshakeTimeoutMillis <= 0L || localHandshakePromise.isDone()) {
            return;
        }
        final Future<?> timeoutFuture = this.ctx.executor().schedule((Runnable)new Runnable() {
            @Override
            public void run() {
                if (!localHandshakePromise.isDone() && localHandshakePromise.tryFailure(new WebSocketServerHandshakeException("handshake timed out"))) {
                    WebSocketServerProtocolHandshakeHandler.this.ctx.flush().fireUserEventTriggered((Object)WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_TIMEOUT).close();
                }
            }
        }, handshakeTimeoutMillis, TimeUnit.MILLISECONDS);
        localHandshakePromise.addListener((GenericFutureListener<? extends Future<? super Void>>)new FutureListener<Void>() {
            @Override
            public void operationComplete(final Future<Void> f) {
                timeoutFuture.cancel(false);
            }
        });
    }
}
