/**
 * 
 */
package org.injac.indexing.util;

import java.util.Enumeration;
import java.util.HashMap;
import java.net.URLDecoder;
import org.apache.webdav.lib.Property;
import org.apache.webdav.lib.WebdavFile;
import org.apache.webdav.lib.methods.DepthSupport;
import org.injac.indexing.exceptions.ExtractMetadataException;

/**
 * @author Francois Jannin
 * extracting metadatas enumerated by document-injac-metadata
 */
public class InjacMetadataExtract extends MetadataExtract {
	private WebdavConnection webdavConnection;
	/**
	 * 
	 */
	public InjacMetadataExtract(WebdavConnection webdavConnection) {
		super();
		this.webdavConnection = webdavConnection;
		// TODO Auto-generated constructor stub
	}
	// filter metadatas from space configuration
	public HashMap getMetadata(WebdavFile webdavFile) throws ExtractMetadataException{
		HashMap allMD = super.getMetadata(webdavFile);
		HashMap result = new HashMap();
		// 1. make a doc from parent space metadata property
		String metas = getSpaceMetadatas(webdavFile);
		if(metas!=null){
			ParseRequiredMetaData parser = new ParseRequiredMetaData(metas);
			java.util.ArrayList required = parser.getMetadataListEdition();
			String name = null;
			String value = null;
			for(int i=0; i<required.size();i++){
				RequiredMetaData reqMD = (RequiredMetaData)required.get(i);
				name =reqMD.getName();
				value = (String)allMD.get(name);
				if(value!=null){
					result.put(name, value);
				}
			}
			// adding root-file-name for further processing
			name = "root-file-name";
			value = (String)allMD.get(name);
			result.put(name, value);
			name = "document-state";
			value = (String)allMD.get(name);
			result.put(name, value);
		}else{
			return allMD;
		}
		return result;
	}
	
	private String getSpaceMetadatas(WebdavFile webdavFile){
		String path = getSpaceParentUrl(getParentUrl());
		int index = path.indexOf("/slide/");
		// no slide context case
		if(index==-1)
			index = path.indexOf("/files");
		
		String ppath = path.substring(index);
		
		
		path = checkPath(path);
		java.util.Vector vprop= new java.util.Vector();
		vprop.add("INJAC:document-injac-metadata");
		try{
			Enumeration props = webdavConnection.getProperties(ppath, DepthSupport.DEPTH_0, vprop);
			Property prop =(Property)props.nextElement();
			return URLDecoder.decode(prop.getPropertyAsString(), "UTF-8");
		}catch(Exception e){
			logger.error("unable to get metadata from "+webdavFile.getPath());
			return null;
		}
	}
	private String getSpaceParentUrl(String docPath){
		
		String result = docPath.substring(0, docPath.lastIndexOf('/'));
		return result;
	}	
}
