package com.fuse.storage;

/*
	FUSE Light Server - multiuser server application
	Copyright (C) 2000 Aapo Kyrola / Sulake Oy  Helsinki, Finland

	This program is free software; you can redistribute it and/or
	modify it under the terms of the GNU General Public License
	as published by the Free Software Foundation; either version 2
	of the License, or (at your option) any later version.

	This program 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 General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program; if not, write to the Free Software
	Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
*/


import java.util.*;
import java.rmi.*;

import com.fuse.Log;

/**
  * DatabaseProxy returns an RMI/local-reference to the FUSEDatabase.
  * It caches the rmi-reference for couple of minutes.
  * @author Aapo Kyrola
  */
public class DatabaseProxy {
	private String rmiUrl;
	
	public DatabaseProxy(String rmiUrl) {
		this.rmiUrl = rmiUrl;	
	}
	
	/** 
	  * Returns the reference to the database. May return null! 
	  */
	public synchronized FUSEDatabase getDatabase() {
		// temporary solution!
		// return com.fuse.storage.sql.SQLDatabaseImpl.getLocalInstance(); 
		
		if (System.currentTimeMillis() - lastReferenceTime > 1000*120 || reference == null) {
			refetchReference();
		}
		return reference;
	}
	
	/* If the reference seems to be broken, call this */
	public synchronized void refetchReference() {
		if (rmiUrl == null) {
			Log.status("WARNING: RMI url to the database not defined!");
			return;
		}
		try {
			if (!rmiUrl.equals("local")) {
				reference = (FUSEDatabase) Naming.lookup(rmiUrl);	
			} else reference = com.fuse.storage.sql.SQLDatabaseImpl.getLocalInstance();
		} catch (Exception re) {
			Log.error(re);
		}
	}
	
	
	FUSEDatabase reference = null;
	public long lastReferenceTime = 0;
}
