package xdi2.core.impl.redis;

import java.io.IOException;

import org.apache.commons.codec.binary.Base64;

import redis.clients.jedis.Jedis;
import xdi2.core.GraphFactory;
import xdi2.core.impl.keyvalue.AbstractKeyValueGraphFactory;
import xdi2.core.impl.keyvalue.KeyValueStore;

/**
 * GraphFactory that creates graphs in Redis.
 * 
 * @author markus
 */
public class RedisGraphFactory extends AbstractKeyValueGraphFactory implements GraphFactory {

	public static final boolean DEFAULT_SUPPORT_GET_CONTEXTNODES = true; 
	public static final boolean DEFAULT_SUPPORT_GET_RELATIONS = true; 

	public static final String DEFAULT_HOST = "localhost";
	public static final Integer DEFAULT_PORT = null;

	private String host;
	private Integer port;

	public RedisGraphFactory() {

		super(DEFAULT_SUPPORT_GET_CONTEXTNODES, DEFAULT_SUPPORT_GET_RELATIONS);

		this.host = DEFAULT_HOST;
		this.port = DEFAULT_PORT;
	}

	@Override
	protected KeyValueStore openKeyValueStore(String identifier) throws IOException {

		// create jedis

		Jedis jedis = this.getPort() == null ? new Jedis(this.getHost()) : new Jedis(this.getHost(), this.getPort().intValue());

		// create prefix
		
		String prefix = new String(Base64.encodeBase64(identifier.getBytes("UTF-8")), "UTF-8") + ".";
		
		// open store

		KeyValueStore keyValueStore;

		keyValueStore = new RedisKeyValueStore(jedis, prefix);
		keyValueStore.init();

		// done

		return keyValueStore;
	}

	public String getHost() {

		return this.host;
	}

	public void setHost(String host) {

		this.host = host;
	}

	public Integer getPort() {

		return this.port;
	}

	public void setPort(Integer port) {

		this.port = port;
	}
}

@@ -1204,18 +1204,16 @@
 prefix%0D%0A
-%09%09
 %0D%0A%09%09Stri
@@ -1223,16 +1223,42 @@
 prefix =
+ identifier == null ? %22%22 :
  new Str
@@ -1329,18 +1329,16 @@
 + %22.%22;%0D%0A
-%09%09
 %0D%0A%09%09// o

support for null graph identifire