package MV3500Cohort2024JulySeptember.homework2.Yu;

import java.io.*;
import java.net.*;

/**
 * @author Jin Hong Yu
 */
public class YuHW2HandlerThread extends Thread
{
    /** The socket connection to a client */
    Socket socket;
    
    /** 
     * The thread constructor creates the socket from a ServerSocket, waiting for the client to connect,
     * and passes that socket when constructing the thread responsible for handling the connection.
     * 
     * @param socket The socket connection handled by this thread
     */
    YuHW2HandlerThread(Socket socket)
    {
        this.socket = socket;
    }
    /**
     * Program invocation and execution starts here - but is illegal and unwanted, so warn the unsuspecting user!
     * @param args command-line arguments
     */
    public static void main(String[] args)
    {
        System.out.println ("*** YuHW2HandlerThread is not a standalone executable progam.");
        System.out.println ("*** Please run TcpExample4DispatchServer instead... now exiting.");
    }
    
    /** Handles one connection. We add an artificial slowness
     * to handling the connection with a sleep(). This means
     * the client won't see a server connection response for ten seconds (default).
     */
    // @overriding run() method in Java Thread class is deliberate
    @Override 
    public void run()
    {
    try {
        System.out.println(YuHW2HandlerThread.class.getName() + " starting to handle a thread...");

        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        PrintStream ps = new PrintStream(socket.getOutputStream());

        // Sequence of the Knock Knock joke
        String clientMessage = in.readLine();
        System.out.println("Client: " + clientMessage);

        if ("Knock Knock".equals(clientMessage)) {
            ps.println("Who's there?");
            ps.flush();
        }

        clientMessage = in.readLine();
        System.out.println("Client: " + clientMessage);

        if ("Hatch".equals(clientMessage)) {
            ps.println("Hatch who?");
            ps.flush();
        }

        clientMessage = in.readLine();
        System.out.println("Client: " + clientMessage);

        if ("God Bless You!".equals(clientMessage)) {
            System.out.println("Joke sequence complete.");
        }

        socket.close(); // all clear, no longer need socket
        System.out.println(YuHW2HandlerThread.class.getName() + " finished handling a thread, now exit.");
    } catch(IOException e) {
        System.out.println("Problem with " + YuHW2HandlerThread.class.getName() + " networking:");
        System.out.println("Error: " + e);
        if (e instanceof java.net.BindException) {
            System.out.println("*** Be sure to stop any other running instances of programs using this port!");
        }
      }
    }
}