package wash.control;

import static wash.control.WashingMessage.Order.WATER_IDLE;

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

public class ControllerWater extends ActorThread<WashingMessage> {

    WashingMessage.Order o;
    WashingMessage m;
    WashingMessage temp;
    WashingIO io;

    Order waterState = WATER_IDLE;
    boolean ackSent = true;

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

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

    @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() != waterState) {
                    waterState = m.order();
                }

                switch (waterState) {
                    case Order.WATER_DRAIN -> {
                        io.drain(true);
                        io.fill(false);
                        if (io.getWaterLevel() == 0 && !ackSent)
                            sendAck();
                    }
                    case Order.WATER_FILL -> {
                        io.drain(false);

                        if (io.getWaterLevel() < 19)
                            io.fill(true);
                        else {
                            io.fill(false);
                            if (!ackSent) {
                                sendAck();
                            }
                        }
                    }
                    case Order.WATER_IDLE -> {
                        io.drain(false);
                        io.fill(false);
                    }
                    default -> {
                        continue;
                    }
                }
            } catch (Exception e) {
                System.out.println("Exception: " + e);
            }
        }
    }
}
