package ru.kirillius.cooler.controller.CLI;

import com.fazecast.jSerialComm.SerialPort;
import ru.kirillius.cooler.controller.Application;

public class PortSelectionMenu extends Menu<SerialPort> {
    public PortSelectionMenu() {
        super("Select serial port");
        reload();
    }

    private void reload() {
        add(new SimpleMenuItem<>(null, "Refresh..."));
        if (Application.DEBUG) {
            add(new SimpleMenuItem<>(null, "debug/virtual"));
        }
        try {
            for (SerialPort port : SerialPort.getCommPorts()) {
                add(new SimpleMenuItem<>(port, port.getSystemPortName()));
            }
        } catch (Throwable t) {
            throw new RuntimeException("Failed to get serial port list", t);
        }
    }

    @Override
    protected SerialPort OnSelect(int index, MenuItem<SerialPort> item, SerialPort value) {
        if (value == null && index == 0) {
            removeAll();
            reload();
        } else {
            close();
            return value;
        }
        return null;
    }
}
