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

import static io.webfolder.cdp.logger.CdpLoggerType.Log4j;

import java.net.URL;
import java.util.List;

import io.webfolder.cdp.Example;
import io.webfolder.cdp.Launcher;
import io.webfolder.cdp.Options;
import io.webfolder.cdp.session.Session;
import io.webfolder.cdp.session.SessionFactory;
import io.webfolder.cdp.type.target.TargetInfo;

@Example
public class ConnectExistingSession2 {

    public static void main(String[] args) {
        Options options = Options.builder()
                                    .loggerType(Log4j)
                            .build();

        Launcher launcher = new Launcher(options);

        URL url = ConnectExistingSession2.class.getResource("/connect-existing-session.html");

        try (SessionFactory factory = launcher.launch();
                            Session session = factory.create()) {
            session.navigate(url.toString());
            session.waitDocumentReady();
            session.click("a");

            // prints "1", getSessions() returns only connected sessions
            System.out.println(factory.getSessions().size());

            // list all pages & windows
            List<TargetInfo> targets = session.getCommand().getTarget().getTargets();
            // this will print "2"
            System.out.println(targets.size());

            TargetInfo target = targets.stream()
                                        .filter(p -> p.getUrl().contains("yahoo"))
                                        .findFirst()
                                        .get();

            Session yahooSession = factory.connect(target.getTargetId());
            yahooSession.waitDocumentReady();

            // prints "2"
            System.out.println(factory.getSessions().size());

            yahooSession.close();

            // prints "1"
            System.out.println(factory.getSessions().size());

            session.wait(1000);
        } finally {
            launcher.kill();
        }
    }
}