/*
Copyright (C) 2000-2010  Ministere de la culture et de la communication (France), AJLSM
See LICENCE file
*/
package fr.gouv.culture.sdx.thesaurus;


import fr.gouv.culture.sdx.utils.lucene.LuceneDataStore;
import fr.gouv.culture.sdx.utils.constants.Node;
import fr.gouv.culture.sdx.document.IndexableFieldProperty;
import org.apache.lucene.document.Document;
import org.xml.sax.SAXException;


public class LuceneConcept extends AbstractConcept {


	protected Document luceneDoc = null;
	protected final String idKey = LuceneDataStore.ID_FIELD;

	public LuceneConcept() {
		super();
	}

	public LuceneConcept(Document lDoc) {
		if (lDoc != null)
			this.luceneDoc = lDoc;
	}

	/**Provides the value from a lucene data object if it exists*/
	public String getValue() {
		if (luceneDoc != null)
			return luceneDoc.get(valueKey);
		return super.value;
	}

	/**Provides the xml:lang otherwise it returnts the value of the class variable from a lucene data object if it exists*/
	public String getXmlLang() {
		if (luceneDoc != null)
			return luceneDoc.get(xmlLangKey);
		return super.xmlLang;
	}

	/**
	 * @deprecated Should not be used as int/relation string mapping should be handled by
	 * the Thesaurus as it defines the relationship between itself and a Concept, so the
	 * Thesaurus shoud to the int to String conversion before calling getRelations(String type)
	 */
	public String[] getRelations(int type) {
			return null;
	}

	public String[] getRelations(String type) {
		if (luceneDoc == null)
			return null;
		return luceneDoc.getValues(type);
	}
	public String getId() {
		if (luceneDoc != null)
			return luceneDoc.get(idKey);
		return super.getId();
	}

	public void endElement(String uri, String loc, String raw)
			throws SAXException {
		if (DOC_NAMESPACE.equals(uri)) {
			if (TERM.equals(loc) || Node.Name.RELATION.equals(loc) || Node.Name.P.equals(loc) || RELATION_USED_FOR.equals(loc)) {
				if (super.currentFieldName != null && super.currentFieldName.equalsIgnoreCase(TERM)) {
					if (super.characterBuffer != null && super.characterBuffer.length() > 0)
						super.properties.add(new IndexableFieldProperty(LuceneThesaurus.FIELD_NAME_FTERM, super.characterBuffer.toString()));
				}

				if (super.currentFieldName != null && super.currentFieldName.equalsIgnoreCase(RELATION_USED_FOR)) {
					//adding the uf relation value as the fuf field for field level searches
					if (super.characterBuffer != null && super.characterBuffer.length() > 0)
						properties.add(new IndexableFieldProperty(LuceneThesaurus.FIELD_NAME_FUF, super.characterBuffer.toString()));
				}
			}
			super.endElement(uri, loc, raw);
		} else
			super.endElement(uri, loc, raw);

	}


}
