package appengine.util;

import java.util.ArrayList;
import java.util.List;

import com.google.appengine.api.datastore.dev.LocalDatastoreService;
import com.google.appengine.tools.development.ApiProxyLocalImpl;
import com.google.apphosting.api.ApiProxy;
import com.google.apphosting.api.ApiProxy.Environment;
import com.google.apphosting.api.DatastorePb.GetSchemaRequest;
import com.google.apphosting.api.DatastorePb.Schema;
import com.google.storage.onestore.v3.OnestoreEntity.EntityProto;
import com.google.storage.onestore.v3.OnestoreEntity.Property;
import com.google.storage.onestore.v3.OnestoreEntity.Path.Element;

/**
 * ローカルのDatastoreファイルをあれこれするためのユーティリティクラス。
 * @author shin1ogawa
 */
public class LocalDataFileUtil {

	private LocalDataFileUtil() {
	}

	/**
	 * @param appId
	 * @return Kindの一覧
	 */
	public static String[] getKinds(String appId) {
		LocalDatastoreService datastoreService =
				(LocalDatastoreService) ((ApiProxyLocalImpl) ApiProxy.getDelegate())
					.getService("datastore_v3");
		Schema schema = datastoreService.getSchema(null, new GetSchemaRequest().setApp(appId));
		List<EntityProto> entityProtoList = schema.kinds();
		List<String> kindList = new ArrayList<String>(entityProtoList.size());
		for (EntityProto entityProto : entityProtoList) {
			List<?> path = entityProto.getKey().getPath().elements();
			Element element = (Element) path.get(path.size() - 1);
			kindList.add(element.getType());
		}
		return kindList.toArray(new String[0]);
	}

	/**
	 * @param environment
	 * @param kind
	 * @return 指定されたKindの属性一覧
	 */
	public static String[] getProperties(Environment environment, String kind) {
		LocalDatastoreService datastoreService =
				(LocalDatastoreService) ((ApiProxyLocalImpl) ApiProxy.getDelegate())
					.getService("datastore_v3");
		Schema schema =
				datastoreService.getSchema(null, new GetSchemaRequest().setApp(environment
					.getAppId()));
		List<EntityProto> entityProtoList = schema.kinds();
		for (EntityProto entityProto : entityProtoList) {
			List<?> path = entityProto.getKey().getPath().elements();
			Element element = (Element) path.get(path.size() - 1);
			String type = element.getType();
			if (kind.equals(type)) {
				List<Property> properties = entityProto.propertys();
				String[] propertyNames = new String[properties.size()];
				for (int i = 0; i < propertyNames.length; i++) {
					propertyNames[i] = properties.get(i).getName();
				}
				return propertyNames;
			}
		}
		throw new RuntimeException("kind \"" + kind + "\" is not found.");
	}
}
