
import java.net.*;
import java.io.*;
import java.text.*;
import java.util.*;

class Server {
  public static void main(String[] args) throws Exception { // We basically ignore every error that could happen in here, by declaring that main can throw them

    int port = 12345; //basic server:
    ServerSocket ss = new ServerSocket(port);
    System.out.println("Time server online.");

    String time;

    while (true) {//forever loop
      Socket s = ss.accept();//get new client

      //init IO
      Scanner sc = new Scanner(s.getInputStream());
      PrintWriter pw = new PrintWriter(s.getOutputStream());

      //read the client's requested offset:
      String toAdd = sc.nextLine();
      //(redacted, as the assignment isn't to sync but to offset time) We really do not want to handle the case where the client's guess is correct. It's much simpler to just sync anyway.

      String[] parts = toAdd.split(":");
      int hour = Integer.parseInt(parts[0]);
      int minute = Integer.parseInt(parts[1]);
      System.out.println("Client requested current time with offset: (Hour: "
                         + hour + " Minute: " + minute + ")");

      //(I got some of this code from stackoverflow.com)
      Calendar cal = Calendar.getInstance(); // Calendar knows the time on this machine.
      cal.add(Calendar.HOUR, hour); //Update time with the offset requested by client
      cal.add(Calendar.MINUTE, minute); //minutes too
      SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm"); // We need it formatted hour:minute
      time = simpleDateFormat.format(cal.getTime()); //this is what we'll send.

      //tell client what the time + offset is:
      pw.println(time);
      pw.flush();

      //log:
      System.out.println("Sent time: " + time);

      //close current client
      pw.close();
      sc.close();
      s.close();

      //forever loop
    }
  }
}
