package GPIO;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

public class LedController {

    DatagramSocket socket;
    private final InetSocketAddress target;

    /**
     * Initialize LedController
     * @param targetip Target IP where the LedController is located, usually localhost
     * @param targetport Target port where the LedController is listening
     */
    public LedController(String targetip, int targetport){
        target = new InetSocketAddress(targetip, targetport);
        try{
            socket = new DatagramSocket();
        } catch (Exception e){
            System.out.println("Error creating socket: "+e.getMessage());
        }
    }

    /**
     * Set the state of a LED
     * @param type Type of LED
     * @param state State of LED
     * @return True if the command was sent successfully
     */
    public boolean SetLed(LedType type, LedState state){
        if (IsOpened()){
            byte[] cmd = new byte[]{(byte)0xCC, type.value, state.value, (byte)0xDD};
            try{
                DatagramPacket packet = new DatagramPacket(cmd, cmd.length, target);
                socket.send(packet);
                return true;
            } catch (Exception e){
                System.out.println("Error sending packet: "+e.getMessage());
            }
        }
        return false;

    }

    /**
     * Check if LedController is opened
     * @return true if opened
     */
    public boolean IsOpened(){
        return socket!=null;
    }

    /**
     * Close LedController
     */
    public void Close(){
        if (socket!=null) socket.close();
    }
}
