package wash.control;

import actor.ActorThread;
import wash.io.WashingIO;
import wash.control.WashingMessage.Order;

public final class ControllerTemp extends ActorThread<WashingMessage> {
    private WashingIO io;
    private WashingMessage m;
    private WashingMessage temp;
    private boolean ackSent = true;
    private Order heaterState = Order.TEMP_IDLE;

    public ControllerTemp(WashingIO io) {
        this.io = io;
    }

    protected void sendAck() {
        m.sendAck(this);
        ackSent = true;
    }

    @Override
    public void run() {
        while (true) {
            try {
                temp = receiveWithTimeout(10000 / Settings.SPEEDUP);

                // If there is a new message, swap
                if (temp != null) {
                    m = temp;
                    ackSent = false; // We have a new order
                }

                // If this message is not the same as last time
                if (m != null && m.order() != heaterState) {
                    heaterState = m.order();
                }

                switch (heaterState) {
                    case Order.TEMP_SET_40 -> {
                        if (io.getTemperature() <= 39) {
                            io.heat(true);
                        } else {
                            io.heat(false);
                            if (!ackSent)
                                sendAck();
                        }
                    }
                    case Order.TEMP_SET_60 -> {
                        if (io.getTemperature() <= 59) {
                            io.heat(true);
                        } else {
                            io.heat(false);
                            if (!ackSent)
                                sendAck();
                        }
                    }
                    case Order.TEMP_IDLE -> {
                        io.heat(false);
                        if (!ackSent)
                            sendAck();
                    }
                    default -> {
                        continue;
                    }
                }
            } catch (Exception e) {
                System.out.println("Exception: " + e);
            }
        }
    }
}
