// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
package jcademo.rainbound.udp;

import java.io.IOException;
import java.net.DatagramSocket;

import javax.resource.spi.UnavailableException;
import javax.resource.spi.endpoint.MessageEndpointFactory;
import javax.resource.spi.work.Work;

public class UDPClientWorker implements Work {
	private MessageEndpointFactory mepf;
	private TestSpec as;
	private DatagramSocket dgs;
	private UDPUtil.DataAndOrigin dao;
	public UDPClientWorker(MessageEndpointFactory mepf, TestSpec as, DatagramSocket dgs, UDPUtil.DataAndOrigin dao) {
		this.mepf = mepf;
		this.as = as;
		this.dgs = dgs;
		this.dao = dao;
	}
	@Override
	public void run() {
		try {
			if(as.isDebug()) {
				System.out.println("Client handler starting");
			}
			// parse id and numbers to add
			String text = dao.getData();
			String[] textparts = text.split("\r\n");
			String id = textparts[0];
			String line = textparts[1];
			String[] lineparts = line.split(" ");
			int a = Integer.parseInt(lineparts[0]);
			int b = Integer.parseInt(lineparts[1]);
			// allocate, use and release MDB
			TestListener mep = (TestListener)mepf.createEndpoint(null);
			mep.setDebug(as.isDebug());
			int c = mep.add(a, b);
			mep.release();
			// send response with line with id and line with result
			UDPUtil.send(dgs, new UDPUtil.DataAndOrigin(id + "\r\n" + Integer.toString(c), dao.getAddress(), dao.getPort()));
			if(as.isDebug()) {
				System.out.println("Client handler done");
			}
		} catch (UnavailableException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	@Override
	public void release() {
	}
}
