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


import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.*;


/*
 * The class simulate broken HTTP server
 *
 */
public class BrokenHttpServer extends AbstractHttpSockServer {

    public static enum ACTIONS {
        CLOSE_SOCKET, SHUTDOWN_OUTPUT, REFUSE_CONNECTION
    };

    private ACTIONS action = ACTIONS.REFUSE_CONNECTION;

    public BrokenHttpServer(int port) throws IOException {
        super(port);
    }

    public void setAction(ACTIONS action) {
        this.action = action;
    }

    @Override
    public void run() {
        printStartMessage();

        ServerSocket socket;

        try {
            socket = new ServerSocket(getPort(),50,InetAddress.getLoopbackAddress());
        } catch (IOException e) {
            System.out.println("Cannot create server socket" + e);
            return;
        }

        // the main server loop that accepts client connections
        while (!Thread.interrupted()) {
            try {
                switch (action) {
                case SHUTDOWN_OUTPUT:
                    socket.accept().shutdownOutput();
                    break;
                case CLOSE_SOCKET:
                    socket.accept().close();
                    break;
                case REFUSE_CONNECTION:
                default:
                    socket.close();
                    break;
                }
            } catch (IOException e) {
                System.out.println("Cannot accept client connection" + e);
            }
        }
    }

    @Override
    protected Runnable createClientConnectionHandler(final Socket socket) {
        return new Runnable() {

            @Override
            public void run() {
            }
        };
    }

    @Override
    protected void printStartMessage() {
        System.out.println("Broken HTTP server has been started on {0} port" + getPort());
    }
}
