/*
 * https://webfolder.io/license.html
 */
package io.webfolder.cdp.channel;

import static io.webfolder.cdp.channel.ChannelFactory.MAX_PAYLOAD_SIZE;

import io.netty.channel.EventLoopGroup;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpClient;
import io.vertx.core.http.HttpClientOptions;
import io.webfolder.cdp.Example;
import io.webfolder.cdp.Launcher;
import io.webfolder.cdp.session.Session;
import io.webfolder.cdp.session.SessionFactory;

@Example
public class VertxWebSocketConnection {

    public static void main(String[] args) {
        
        final boolean useNetty = true;

        Vertx vertx = Vertx.vertx();

        ChannelFactory channelFactory;

        HttpClient httpClient = null;
        if ( ! useNetty ) {
            HttpClientOptions options = new HttpClientOptions()
                                            .setMaxWebSocketMessageSize(MAX_PAYLOAD_SIZE)
                                            .setMaxWebSocketFrameSize(MAX_PAYLOAD_SIZE);
            httpClient = vertx.createHttpClient(options);
            channelFactory = new VertxWebSocketFactory(httpClient);
        } else {
            EventLoopGroup eventLoopGroup = vertx.nettyEventLoopGroup();
            channelFactory = new NettyWebSocketChannelFactory(eventLoopGroup);
        }

        Launcher launcher = new Launcher(channelFactory);

        try (SessionFactory factory = launcher.launch();
                            Session session = factory.create()) {
            session.navigate("https://webfolder.io?cdp4j");
            session.waitDocumentReady();
            String content = session.getContent();
            System.out.println(content);
        } finally {
            if ( httpClient != null ) {
                httpClient.close();
            }
            vertx.close();
            launcher.kill();
        }
    }
}