package MV3500Cohort2024JulySeptember.homework1.Williams;

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

public class Server {

    private static int runningTotal = 0; // Initialize running total

    public Server() {
        // default constructor
    }

    public static void main(String[] args) {
        try {
            System.out.println(Server.class.getName() + " has started...");
            ServerSocket serverSocket = new ServerSocket(2317);
            int serverLoopCount = 0;

            while (true) {
                try (Socket clientConnectionSocket = serverSocket.accept(); BufferedReader br = new BufferedReader(new InputStreamReader(clientConnectionSocket.getInputStream())); PrintStream ps = new PrintStream(clientConnectionSocket.getOutputStream())) {

                    serverLoopCount++;

                    // Read the number sent by the client
                    String input = br.readLine();
                    if (input == null) {
                        System.err.println("Received null input, skipping this client.");
                        continue;
                    }

                    int clientNumber;
                    try {
                        clientNumber = Integer.parseInt(input);
                    } catch (NumberFormatException e) {
                        System.err.println("Invalid input received: " + input + ". Error: " + e.getMessage());
                        ps.println("Invalid number format: " + input);
                        continue;
                    }

                    // Update the running total
                    int clientNumberSqr = clientNumber * clientNumber;
                    runningTotal += clientNumber;

                    // Send back the updated total and squared number
                    ps.println("Client sent: " + clientNumber + ", client number squared was: " + clientNumberSqr + ", Running total: " + runningTotal);
                    System.out.println("Client sent: " + clientNumber + ", Running total: " + runningTotal);

                    InetAddress localAddress = clientConnectionSocket.getLocalAddress();
                    InetAddress remoteAddress = clientConnectionSocket.getInetAddress();
                    int localPort = clientConnectionSocket.getLocalPort();
                    int remotePort = clientConnectionSocket.getPort();

                    System.out.print("Server loop " + serverLoopCount + ": ");
                    System.out.println(Server.class.getName() + " socket pair showing host name, address, port:");
                    System.out.println("  (( "
                            + localAddress.getHostName() + "=" + localAddress.getHostAddress() + ", " + localPort + " ), ( "
                            + remoteAddress.getHostName() + "=" + remoteAddress.getHostAddress() + ", " + remotePort + " ))");

                    if (localAddress.getHostName().equals(localAddress.getHostAddress())
                            || remoteAddress.getHostName().equals(remoteAddress.getHostAddress())) {
                        System.out.println("  note HostName matches address if host has no DNS name");
                    }
                } catch (IOException e) {
                    System.err.println("Problem handling client connection: " + e.getMessage());
                }
            }
        } catch (IOException e) {
            System.err.println("Problem with " + Server.class.getName() + " networking: " + e);

            if (e instanceof java.net.BindException) {
                System.err.println("*** Be sure to stop any other running instances of programs using this port!");
            }
        }
    }
}