import clock.AlarmClockEmulator;
import clock.io.Choice;
import clock.io.ClockInput;
import clock.io.ClockInput.UserInput;
import clock.io.ClockOutput;

// Semaphore
import java.util.concurrent.Semaphore;

public class ClockMain {

    private static AlarmClockEmulator emulator = new AlarmClockEmulator();
    private static ClockInput in = emulator.getInput();
    private static ClockOutput out = emulator.getOutput();

    static Semaphore sem = in.getSemaphore();
    static Monitor monitor = new Monitor(00, 00, 00, out);

    public static void main(String[] args) throws InterruptedException {
        Thread clockThread = new Thread(new ClockThread(monitor, out));

        while (true) {
            sem.acquire();

            UserInput userInput = in.getUserInput();
            Choice choice = userInput.choice();

            int h = userInput.hours();
            int m = userInput.minutes();
            int s = userInput.seconds();

            switch (choice) {
                case SET_TIME -> {
                    monitor.setTime(h, m, s);
                    out.displayTime(h, m, s);

                    // Kick off the clock thread if it's not already running
                    if (!clockThread.isAlive())
                        clockThread.start();
                }
                case SET_ALARM -> {
                    monitor.setAlarm(h, m, s);
                }
                case TOGGLE_ALARM -> {
                    monitor.toggleAlarm();
                    out.setAlarmIndicator(monitor.getAlarmStatus());
                }
            }

            System.out.println("choice=" + choice + " h=" + h + " m=" + m + " s=" + s);
        }
    }
}
