package de.ctdo.bunti.artnet;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import de.ctdo.bunti.artnet.packets.ArtNetPacket;

@Component
public class ArtNetSocketImpl implements ArtNetSocket {
	private final Logger logger = LoggerFactory.getLogger(getClass());
	public static final int DEFAULT_PORT = 0x1936;
	private DatagramSocket socket;
	
	public ArtNetSocketImpl() {
		try {
			socket = new DatagramSocket();
			
			
		} catch (SocketException e) {

			// TODO
			logger.debug(e.getMessage(), e.getStackTrace());
		}
		
	}

	@Override
	public final boolean unicastPacket(ArtNetPacket pack, String address) {

        if(socket != null) {

            InetAddress targetAdress;
            try {
                targetAdress = InetAddress.getByName(address);

                DatagramPacket packet = new DatagramPacket(pack.getRawData(), pack.getLength(), targetAdress, DEFAULT_PORT);

                socket.send(packet);
                //socket.send(packet, targetAdress);

                return true;

            } catch (UnknownHostException e) {
                logger.error(e.getMessage(), e);
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }
        }
		
		return false;
	}
	

}
