package wash.control;

import actor.ActorThread;
import wash.io.WashingIO;
import wash.program.*;
import wash.simulation.WashingSimulator;

public class Wash {

    public static void main(String[] args) throws InterruptedException {
        WashingSimulator sim = new WashingSimulator(Settings.SPEEDUP);

        WashingIO io = sim.startSimulation();

        ActorThread<WashingMessage> temp = new ControllerTemp(io);
        ActorThread<WashingMessage> water = new ControllerWater(io);
        ActorThread<WashingMessage> spin = new ControllerSpin(io);

        temp.start();
        water.start();
        spin.start();

        // Instantiated to avoid nullchecking in the interrupt inside the loop
        ActorThread<WashingMessage> t = new EmptyProgram();

        outer: while (true) {
            int n = io.awaitButton();
            t.interrupt(); // Immediately abort previous action, t != null here
            System.out.println("user selected program " + n);

            // if the user presses buttons 1-3, start a washing program
            // if the user presses button 0, and a program has been started, stop it

            switch (n) {
                case 0 -> t.interrupt();
                case 1 -> t = new WashingProgram1(io, temp, water, spin);
                case 2 -> t = new WashingProgram2(io, temp, water, spin);
                case 3 -> t = new WashingProgram3(io, temp, water, spin);
                default -> {
                    System.out.println("Invalid program number");
                    break outer;
                }
            }

            if (!t.isInterrupted())
                t.start();
        }

        temp.interrupt();
        water.interrupt();
        spin.interrupt();

        if (t != null)
            t.interrupt();
    }
};
