package com.dokukino.genkidama;

import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import ow.id.ID;

public class PutTask implements Runnable {
	public static Log logger = LogFactory.getLog(PutTask.class);
	private String id;

	public PutTask(String id) {
		this.id = id;
	}

	@SuppressWarnings("unchecked")
	@Override
	public void run() {
		GenkidamaManager manager = GenkidamaManager.getInstance();
		if (logger.isDebugEnabled())
			logger.debug("PutTask takes " + id);
		while (!manager.isConnected()) {
			if (logger.isDebugEnabled())
				logger.debug("PutTask waiting connection");
			try {
				ExecutorService putExecutor = manager.getPutExecutor();
				synchronized (putExecutor) {
					putExecutor.wait();
				}
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		ID key = ID.getSHA1BasedID(("nc:" + id).getBytes());
		logger.info("DHT put: nc:" + id);
		String uri = "http://" + manager.getExternalAddress() + ":"
				+ manager.getDataPort() + "/nc/" + id;
		while (true) {
			try {
				manager.getDht().put(key, uri);
				break;
			} catch (Exception e) {
				// TODO Auto-generated catch block
				if (logger.isErrorEnabled())
					logger.error("Error Occurs:", e);
			}
		}
		List params = new ArrayList();
		params.add(manager.getRingPort());
		params.add(VersionInfo.APPLICATION_MINOR_VERSION);
		params.add("nc:" + id);
		try {
			XmlRpcInvoker.invokeAsync("onlineData.register", params);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			if (logger.isErrorEnabled())
				logger.error("Error Occurs:", e);
		}
	}
}
