package org.mote.wiimote.whiteboard;

import org.mote.wiimote.whiteboard.preferences.WWPreferences;

import wiiremotej.WiiRemote;
import wiiremotej.WiiRemoteJ;

public class WiimoteConnector {
	
	private WiimoteDataHandler dh;
	
	public WiimoteConnector(WiimoteDataHandler dh) {
		this.dh = dh;
	}
	
	public void connect() {
		if (!WWPreferences.WIIMOTE_BT_ADDRESSES.isEmpty()) {
			WiimoteWhiteboard.getLogger().info(String.format("Directly connecting to bluetooth address(es) %s.", WWPreferences.WIIMOTE_BT_ADDRESSES));
			for (int i = 0; i < Math.min(WWPreferences.WIIMOTE_BT_ADDRESSES.size(), WWPreferences.WIIMOTES); i++) {
				connect(WWPreferences.WIIMOTE_BT_ADDRESSES.get(i));
			}
		} else {
			WiiRemoteJ.findRemotes(dh, WWPreferences.WIIMOTES);
		}
	}
	
	private void connect(final String address) {
		new Thread(new Runnable() {
			private boolean done = false;
			public void run() {
				while (!done) {
					try {
						WiiRemote r = WiiRemoteJ.connectToRemote(address);
						if (r != null && r.isConnected()) {
							done = true;
							dh.addRemote(r);
						}
					} catch (Exception e) {
//						if (e.getCause().getMessage().startsWith("Failed to open baseband connection")) {
//							// apparently simple timeout error
//						} else {
//							// "regular" connection error
//						}
						try {
							Thread.sleep(1000);
						} catch (InterruptedException e1) {
							e1.printStackTrace();
						}						
					}
				}
			}
		}).start();
	}

}
