/*
 *============================================================================
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of version 2.1 of the GNU Lesser General Public
 * License as published by the Free Software Foundation.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *============================================================================
 * Copyright (C) 2007 Tom Wilkie <tom.wilkie@gmail.com>
 *============================================================================
 */
package com.xensource.xenapi;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import java.util.Vector;

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

public class ConnectionHelper {

    public static class NoConnectionOnThisThreadException extends Exception {
    }

    private static ThreadLocal<ConnectionHelper> instances = 
        new ThreadLocal<ConnectionHelper>();

    private URL url;
    private Session session;

    private ConnectionHelper(URL url) {
        this.url = url;
    }

    public static void setup(String url) throws MalformedURLException {
        ConnectionHelper helper = new ConnectionHelper(new URL(url));
        ConnectionHelper.setConnectionHelper(helper);
    }

    /**
     * Use this method to share connection helpers (and therefore 
     * connections and sessions) across threads.
     */
    public static void setConnectionHelper(ConnectionHelper helper) {
        ConnectionHelper.instances.set(helper);
    }

    /**
     * Like ConnectionHelper.instance, excepts returns null if
     * no instance exists
     */
    public static ConnectionHelper getConnectionHelper() {
        return ConnectionHelper.instances.get();
    }

    /**
     * Get this thread's connection helper
     * @throws NoConnectionOnThisThreadException
     */
    public static ConnectionHelper instance() 
        throws NoConnectionOnThisThreadException {
        ConnectionHelper instance = ConnectionHelper.instances.get();
        if (instance == null) {
        	try {
				ConnectionHelper.setup("http://localhost:9363");
				ConnectionHelper.instance().setSession(Session.loginWithPassword("xen", "password"));
				
				instance = ConnectionHelper.instances.get();
        	} catch (Exception e) {
        		throw new NoConnectionOnThisThreadException();
        	}
        }
        return instance;
    }

    protected String getSession() {
        return this.session.ref;
    }

    public void setSession(Session session) {
        this.session = session;
    }

    public Map dispatch(String method_call, Object[] method_params) 
        throws XmlRpcException {
        XmlRpcClient client = new XmlRpcClient(url);
        
        Vector<Object> params = new Vector<Object>();
        for(Object o : method_params)
        	params.add(o);
        
        try {
			return (Map) client.execute(method_call, params);
		} catch (IOException e) {
			throw new XmlRpcException(0, "IOException");
		}
    }
}
