/*
 * Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

package java.net;

import java.io.IOException;

/*
 * This is a wrapper for methods of PlainSocketImpl class. It is needed to
 * simulate connections delay on Java sockets layer.
 *
 */
class CustomPlainSocketImpl extends PlainSocketImpl {

    private int connectionDelay = 0;

    private String className;

    CustomPlainSocketImpl(int connectionDelay, String className) {
        super(true);
        this.connectionDelay = connectionDelay;
        this.className = className;
    }

    /*
     * The method simulated connection delay if there is specified class in stack
     * trace.
     */
    private void doDelay(int timeout) throws ConnectException {
        // looking for class in stack trace
        boolean found = false;
        if (className != null) {
            for (StackTraceElement stackTraceElement : Thread.currentThread().getStackTrace()) {
                if (className.equals(stackTraceElement.getClassName())) {
                    found = true;
                    break;
                }
            }
        }

        // simulate connecton delay if class was found
        if (found) {
            try {
                if (timeout > 0 && timeout < connectionDelay) {
                    Thread.sleep(timeout);
                    throw new ConnectException("Connection timed out");
                } else {
                    Thread.sleep(connectionDelay);
                }
            } catch (InterruptedException e) {
                // ignore
            }
        }
    }

    @Override
    protected void connect(String host, int port) throws UnknownHostException, IOException {
        doDelay(0);
        super.connect(host, port);
    }

    @Override
    protected void connect(InetAddress address, int port) throws IOException {
        doDelay(0);
        super.connect(address, port);
    }

    @Override
    protected void connect(SocketAddress address, int timeout) throws IOException {
        doDelay(timeout);
        super.connect(address, timeout);
    }

}
