/*
 * This file is part of Nuts Framework.
 * Copyright (C) 2009 Nuts Develop Team.
 *
 * Nuts Framework 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 3 of the License any later version.
 * 
 * Nuts Framework 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 Nuts Framework. If not, see <http://www.gnu.org/licenses/>.
 */
package nuts.gae.dao;

import nuts.core.io.Streams;
import nuts.core.lang.Classes;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import com.google.appengine.api.datastore.DatastoreServiceFactory;

/**
 */
public class GaeDataAccessClientFactory {

	private static Map<String, GaeDataAccessClient> dataAccessClients = new HashMap<String, GaeDataAccessClient>();

	private static final String DEFAULT = "default";
	
	/**
	 * build dataAccessClient object
	 * 
	 * @param name  the configuration file resource name.
	 * @return GaeDataAccessClient instance.
	 */
	public static GaeDataAccessClient buildDataAccessClient(String name) {
		InputStream is = null;
		try {
			Properties p = new Properties();
			if (name != null) {
				is = Classes.getClassLoader().getResourceAsStream(name);
				p.load(is);
			}
			return buildDataAccessClient(name, p);
		}
		catch (IOException e) {
			throw new RuntimeException("Can not load " + name, e);
		}
		finally {
			Streams.safeClose(is);
		}
	}

	/**
	 * build dataAccessClient object
	 * 
	 * @param props properties
	 * @return GaeDataAccessClient instance.
	 */
	public static GaeDataAccessClient buildDataAccessClient(Properties props) {
		return buildDataAccessClient(null, props);
	}
	
	/**
	 * build dataAccessClient object
	 * 
	 * @param name  the dataAccessClient name
	 * @param props properties
	 * @return GaeDataAccessClient instance.
	 */
	public static GaeDataAccessClient buildDataAccessClient(String name, Properties props) {
		GaeDataAccessClient dac = new GaeDataAccessClient(DatastoreServiceFactory.getDatastoreService(), props);
		dac.setName(name == null ? DEFAULT : name);
		dataAccessClients.put(dac.getName(), dac);
		return dac;
	}

	/**
	 * getDataAccessClient
	 * @param name  the gae-datastore.properties configuration file resource name.
	 * @return GaeDataAccessClient instance.
	 */
	public static GaeDataAccessClient getDataAccessClient(String name) {
		GaeDataAccessClient smc = dataAccessClients.get(name == null ? DEFAULT : name);
		if (smc == null) {
			return buildDataAccessClient(name);
		}
		return smc;
	}
}
