/**
 * 
 */
package eu.dnetlib.enabling.manager;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;

import eu.dnetlib.common.utils.xml.xpath.XPathParser;

/**
 * @author dhofar
 *
 */
public class InfoFile {

	private final String infoFileDirPath = "/var/lib/dnet/dms";
	private XPathParser xPathParser;
	private String repositoryId;
	
	public InfoFile(String repoId) throws Exception{
		
		repositoryId = repoId;
		
		File dmsDir = new File (infoFileDirPath);
		if (!dmsDir.exists())
			dmsDir.mkdir();
		
		File repoFile = new File(infoFileDirPath+"/"+repoId);
		if (!repoFile.exists()) {
			FileWriter fstream = new FileWriter(infoFileDirPath+"/"+repoId);
	        BufferedWriter out = new BufferedWriter(fstream);
	        out.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
	        out.write("<infofile>");
	        out.write("<repositoryid>"+repoId+"</repositoryid>");
	        out.write("<mdstoreid></mdstoreid>");
	        out.write("<indexid></indexid>");
	        out.write("<storeidforextraction></storeidforextraction>");
	        out.write("<storeidforextractedft></storeidforextractedft>");
	        out.write("</infofile>");
	        out.close();
		}
		
		xPathParser = new XPathParser(infoFileDirPath+"/"+repoId, true);
		
		
	}
	
	
	
	public void write (String fieldName, String fieldValue) throws Exception {
		
		xPathParser.updateElementValue("//"+fieldName, fieldName, fieldValue, null, null);
		String newXL = xPathParser.getModifiedDocument();
		
		FileWriter fstream = new FileWriter(infoFileDirPath+"/"+repositoryId);
        BufferedWriter out = new BufferedWriter(fstream);
        out.write(newXL);
        out.close();
	}
	
	public String get( String fieldName) throws Exception {
		return xPathParser.getElementValue("//"+fieldName);
		
	}
	
}
