/*
 * Copyright (c) 2009, syuu
 * Licensed under the NicoCache License.
 */

package com.dokukino.genkidama;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;

public class XmlRpcInvoker {
	private static ExecutorService xmlRpcExecutor = Executors.newSingleThreadExecutor();

	@SuppressWarnings("unchecked")
	private static Object invoke(URL url, String method, List params) throws XmlRpcException {
		XmlRpcClientConfigImpl conf = new XmlRpcClientConfigImpl();
		conf.setServerURL(url);
		XmlRpcClient client = new XmlRpcClient();
		client.setConfig(conf);
		return client.execute(method, params);
	}
	
	@SuppressWarnings("unchecked")
	public static Object invoke(String url, String method, List params) throws MalformedURLException, XmlRpcException {
		return invoke(new URL(url), method, params);
	}

	@SuppressWarnings("unchecked")
	public static Object invoke(String method, List params) throws MalformedURLException, XmlRpcException {
		return invoke(DHTConfig.DHT_XMLRPC_URL, method, params);
	}
	
	public static void invokeAsync(URL url, String method, List params) {
		xmlRpcExecutor.execute(new XmlRpcTask(url, method, params));
	}
	
	public static void invokeAsync(String url, String method, List params) throws MalformedURLException {
		invokeAsync(new URL(url), method, params);
	}
	
	public static void invokeAsync(String method, List params) throws MalformedURLException {
		invokeAsync(DHTConfig.DHT_XMLRPC_URL, method, params);
	}
}
