package de.hsadmin.jscli;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

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

public class RpcClient {

	private static final String XMLRPC_URL = "https://config.hostsharing.net:443/hsar/xmlrpc/hsadmin";
	
	private String xmlrpcURL;
	private XmlRpcClient client;

	public RpcClient(CASTicket tgt) throws JSCliException {
		try {
			xmlrpcURL = Config.getInstance().getProperty("xmlrpcURL", XMLRPC_URL);
			XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
			config.setServerURL(new URL(xmlrpcURL));
			config.setEnabledForExtensions(true);
			client = new XmlRpcClient();
			client.setConfig(config);
		} catch (MalformedURLException e) {
			throw new JSCliException(e);
		}
	}
	
	public List<String> listMethods() throws JSCliException {
		List<String> methodList = new ArrayList<String>();
		List<Object> execute = execute("system.listMethods");
		for (Object obj : execute) {
			methodList.add(obj.toString());
		}
		return methodList;
	}

	private List<Object> execute(String method) throws JSCliException {
		return execute(method, new ArrayList<Object>());
	}

	public List<Object> execute(String method, List<?> params) throws JSCliException {
		try {
			Object execute = client.execute(method, params);
			ArrayList<Object> list = new ArrayList<Object>();
			if (execute instanceof Object[]) {
				Object[] resArray = (Object[]) execute;
				for (int idx=0; idx < resArray.length; idx++) {
					list.add(resArray[idx]);				
				}
			}
			return list;
		} catch (XmlRpcException e) {
			throw new JSCliException(e);
		}
	}
	
}
