package de.brightbyte.rdf.aardfark;

import java.net.URI;
import java.util.HashMap;
import java.util.Map;

public abstract class AbstractRdfContext implements RdfContext {
	
	protected Map<String, URI> vocabByName = new HashMap<String, URI>();
	protected Map<URI, String> vocabByURI = new HashMap<URI, String>();
	
	public void addVocablulary(String name, URI uri) throws RdfVocabException {
		if (vocabByName.containsKey(name)) throw new RdfVocabException("already has vocabulary "+name);
		if (vocabByURI.containsKey(uri)) throw new RdfVocabException("already has vocabulary "+uri);
		
		vocabByName.put(name, uri);
		vocabByURI.put(uri, name);
	}

	public String getNameFrom(URI uri) throws RdfVocabException {
		String vocab = getVocabularyFrom(uri);
		//if (vocab==null) throw new RdfVocabException("no such vocabulary: "+uri);
		if (vocab==null) return null;
		
		URI vuri = getVocabularyURI(vocab);
		
		String name = uri.toString().substring(vuri.toString().length());
		return name;
	}

	public URI getURI(String qname) throws RdfVocabException {
		String[] n = qname.split(":");
		if (n.length!=2) throw new IllegalArgumentException("bad qname: "+qname);
		return getURI(n[0], n[1]);
	}

	public URI getURI(String vocab, String name) throws RdfVocabException {
		URI uri = getVocabularyURI(vocab);
		if (uri==null) throw new RdfVocabException("no such vocabulary: "+vocab);
		return getURI(uri, name);
	}

	public URI getURI(URI vocab, String name) {
		return RdfUtil.makeURI(vocab, name);
	}

	public URI getVocabularyURI(String name)  {
		URI uri = vocabByName.get(name);
		//if (uri==null) throw new RdfVocabException("no such vocabulary: "+name);
		return uri;
	}

	public String getVocabularyName(URI uri) {
		String name = vocabByURI.get(uri);
		//if (name==null) throw new RdfVocabException("no such vocabulary: "+name);
		return name;
	}

	public String getVocabularyFrom(URI uri) {
		String u = uri.toString();
		
		for (Map.Entry<String, URI> e : vocabByName.entrySet()) {
			String v = e.getValue().toString();
			
			if (u.startsWith(v)) {
				return e.getKey();
			}
		}
		
		return null;
	}

	public RdfLiteral makeLiteral(String text) throws RdfVocabException {
		return new RdfLiteral(text);
	}
	
	public RdfReference makeReference(String qname) throws RdfVocabException {
		String[] n = qname.split(":");
		if (n.length!=2) throw new IllegalArgumentException("bad qname: "+qname);
		return makeReference(n[0], n[1]);
	}

	public RdfReference makeReference(String vocab, String name) throws RdfVocabException {
		return new RdfReference(this, vocab, name);
	}

}
