package org.openforis.collect.io.metadata;

import java.io.File;
import java.io.FileOutputStream;

import org.apache.commons.io.IOUtils;
import org.openforis.collect.model.CollectSurvey;
import org.openforis.commons.io.csv.CsvWriter;
import org.openforis.concurrency.Job;
import org.openforis.concurrency.Task;
import org.openforis.idm.metamodel.EntityDefinition;
import org.openforis.idm.metamodel.NodeDefinition;
import org.openforis.idm.metamodel.NodeDefinitionVisitor;
import org.openforis.idm.metamodel.Schema;
import org.openforis.idm.metamodel.NodeLabel.Type;

/**
 * 
 * @author S. Ricci
 *
 */
public class SchemaSummaryCSVExportJob extends Job {

	private CollectSurvey survey;
	private File outputFile;
	
	@Override
	protected void initInternal() throws Throwable {
		outputFile = File.createTempFile("collect_schema_export", ".csv");
		super.initInternal();
	}
	
	@Override
	protected void buildTasks() throws Throwable {
		Task task = new Task() {
			@Override
			protected void execute() throws Throwable {
				FileOutputStream out = new FileOutputStream(outputFile);
				final CsvWriter csvWriter = new CsvWriter(out);
				try {
					csvWriter.writeHeaders(new String[] {"id", "path", "name", "type", "label"});
					
					Schema schema = survey.getSchema();
					schema.traverse(new NodeDefinitionVisitor() {
						@Override
						public void visit(NodeDefinition nodeDefn) {
							csvWriter.writeNext(new String[] {
									Integer.toString(nodeDefn.getId()), 
									nodeDefn.getPath(),
									nodeDefn.getName(),
									nodeDefn instanceof EntityDefinition ? "entity": "attribute",
									nodeDefn.getLabel(Type.INSTANCE)
								});
						}
					});
				} finally {
					IOUtils.closeQuietly(csvWriter);
				}
			}
		};
		addTask(task);
	}
	
	public void setSurvey(CollectSurvey survey) {
		this.survey = survey;
	}
	
	public File getOutputFile() {
		return outputFile;
	}
	
}
@@ -37,16 +37,47 @@
 adata;%0A%0A
+import java.io.BufferedWriter;%0A
 import j
@@ -121,16 +121,51 @@
 tStream;
+%0Aimport java.io.OutputStreamWriter;
 %0A%0Aimport
@@ -536,51 +536,8 @@
 or;%0A
-import org.openforis.idm.metamodel.Schema;%0A
 impo
@@ -582,16 +582,59 @@
 el.Type;
+%0Aimport org.openforis.idm.metamodel.Schema;
 %0A%0A/**%0A *
@@ -1187,19 +1187,73 @@
 vWriter(
-out
+new BufferedWriter(new OutputStreamWriter(out)), ',', '%22'
 );%0A%09%09%09%09t
@@ -1316,16 +1316,8 @@
 th%22,
- %22name%22,
  %22ty
@@ -1618,37 +1618,8 @@
 (),%0A
-%09%09%09%09%09%09%09%09%09nodeDefn.getName(),%0A
 %09%09%09%09

Use double quoute for text values in schema summary export, remove "name" column