package de.ctdo.bunti.artnet;

import java.util.Map;

import de.ctdo.bunti.dmx.DMX;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


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

@Component
public class SimpleArtNetSenderImpl implements SimpleArtNetSender {
	
	private ArtNetSocket socket;
	private int sequence = 0;
    	
	@Autowired
	public final void setSocket(ArtNetSocket socket) {
		this.socket = socket;
	}
    
	@Override
	public final boolean sendDMXData(Map<Integer,Integer> dmxData, String adr) {

        if(dmxData == null || adr == null || adr.isEmpty()) {
            return false;
        }

		ArtDmxPacket packet = new ArtDmxPacket();

		byte[] arr = getByteArrayFromDataMap(dmxData);
		
		packet.setSequenceID(sequence++);
		packet.setDMX(arr, arr.length);
        
        return socket.unicastPacket(packet, adr);
    }

    private byte[] getByteArrayFromDataMap(Map<Integer,Integer> dmxData) {
        int size = dmxData.size();
        byte[] arr = new byte[size];

        for (int i = 0; i < dmxData.size(); i++) {
            arr[i] = ByteUtils.uintToByte(dmxData.get(i + DMX.DMX_STARTADDRESS_OFFSET));
        }

        return arr;
    }


}
