package com.hammurapi.render.emf;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;
import org.eclipse.emf.common.util.TreeIterator;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EClassifier;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl;
import org.eclipse.gmf.runtime.notation.Diagram;
import org.eclipse.gmf.runtime.notation.NotationPackage;

import com.hammurapi.common.Context;
import com.hammurapi.common.DefaultContext;
import com.hammurapi.common.IdentityManager;
import com.hammurapi.render.RenderingConstants;
import com.hammurapi.render.RenderingException;
import com.hammurapi.render.ReportGenerator;

/**
 * Generates HTML documentation for ECore models and diagrams.
 * @author Pavel Vlasov
 *
 */
public class EcoreDoc extends Task {
	
	@Override
	public void execute() throws BuildException {
		long start = System.currentTimeMillis();

		if (outputDir==null && outputFile==null) {
			throw new BuildException("Either outputdir or outputfile must be set.");
		}
		
		if (outputDir!=null && !outputDir.exists()) {
			outputDir.mkdirs();
		}
		
		ResourceSet resourceSet = new ResourceSetImpl();
		
		resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(
				Resource.Factory.Registry.DEFAULT_EXTENSION, 
				new XMIResourceFactoryImpl());
		
		resourceSet.getPackageRegistry().put(NotationPackage.eNS_URI, NotationPackage.eINSTANCE);		

		File file = getProject()==null ? new File(diagram) : new File(getProject().getBaseDir(), diagram);
		URI uri = file.isFile() ? URI.createFileURI(file.getAbsolutePath()): URI.createURI(diagram);
				
		Resource resource = resourceSet.getResource(uri, true);
		
		Model model = new Model();
		
		ReportGenerator generator = new ReportGenerator();
		
		Map<String, Object> env = new HashMap<String, Object>();
		env.put(RenderingConstants.RENDER_START, start);
		Context context = new DefaultContext(EcoreDoc.class.getClassLoader(), null);
		IdentityManager<?> identityManager = context.lookup(IdentityManager.class);
		env.put(RenderingConstants.RENDER_HELPER, new ModelRenderHelper(identityManager, outputDir==null ? outputFile.getParentFile() : outputDir, diagramMap, model, env, context, locale, http));
		
		generator.setEnvironment(env);
		generator.setContext(context);
		
		for (EObject obj: resource.getContents()) {
			mapDiagram(obj);
			TreeIterator<EObject> it = obj.eAllContents();
			while (it.hasNext()) {
				EObject next = it.next();
				mapDiagram(next);
			}
		}
				
		
		for (EObject obj: resource.getContents()) {
			if (obj instanceof Diagram) {
				Diagram diagram = (Diagram) obj;
								
				EObject diagramElement = diagram.getElement();
								
				if (diagramElement instanceof EPackage) {					
					EPackage pkg = (EPackage) diagramElement;
					while (pkg.getESuperPackage()!=null) {
						pkg = pkg.getESuperPackage();
					}
					if (!model.getRootPackages().contains(pkg)) {						
						model.getRootPackages().add(pkg);
					}
				} else if (diagramElement instanceof EClassifier) {
					EPackage pkg = ((EClassifier) diagramElement).getEPackage();
					while (pkg.getESuperPackage()!=null) {
						pkg = pkg.getESuperPackage();
					}
					if (!model.getRootPackages().contains(pkg)) {						
						model.getRootPackages().add(pkg);
					}					
				}
				model.getDiagrams().add(diagram);
			} else {
				System.err.println("Unexpected contents: "+obj);
			}
		}
		
		try {
			if (outputDir==null) {
				generator.generate(model, outputFile, "Model documentation", "onepage", http);				
			} else {
				generator.generate(model, outputDir, "Model documentation", http);
			}
		} catch (RenderingException e) {
			throw new BuildException(e);
		}
	}
	
	private String diagram;
	private File outputDir;
	private File outputFile;
	private Locale locale;
	private boolean http;
	
	/**
	 * Sets rendering locale.
	 * @param locale
	 */
	public void setLocale(Locale locale) {
		this.locale = locale;
	}
	
	/**
	 * Source diagram - file or URL
	 * @return
	 */
	public String getDiagram() {
		return diagram;
	}

	/**
	 * Source diagram - file or URL
	 * @param diagram
	 */
	public void setDiagram(String diagram) {
		this.diagram = diagram;
	}

	/**
	 * Output directory
	 * @return
	 */
	public File getOutputDir() {
		return outputDir;
	}

	/**
	 * Output directory
	 * @param outputDir
	 */
	public void setOutputDir(File outputDir) {
		if (outputFile!=null) {
			throw new BuildException("outputdir and outputfile are mutually exclusive");
		}
		this.outputDir = outputDir;
	}
	
	public File getOutputFile() {
		return outputFile;
	}

	/**
	 * If outputfile attribute is set, then the task generates documenation in a single HTML file. Convenient for printing.
	 * @param outputFile
	 */
	public void setOutputFile(File outputFile) {
		if (outputDir!=null) {
			throw new BuildException("outputdir and outputfile are mutually exclusive");
		}
		this.outputFile = outputFile;
	}

	public boolean isHttp() {
		return http;
	}

	/**
	 * If true, outline and contents trees are rendered to use AJAX. It is useful for 
	 * large models, but works only over HTTP.
	 * @param http
	 */
	public void setHttp(boolean http) {
		this.http = http;
	}

	// Assigns ID's to elements for rendering.
	private static Map<EObject, List<Diagram>> diagramMap = new IdentityHashMap<EObject, List<Diagram>>();

	/**
	 * Generates documentation from a diagram file.
	 * Command line parameters: &lt;diagram file&gt; &lt;output dir&gt; [http]
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		System.out.println("Command line parameters: <diagram file> <output dir> [http]");
		System.out.println("Example: mymodel.ecorediag model-doc");
		
		EcoreDoc documenter = new EcoreDoc();
		documenter.setDiagram(args[0]);
		documenter.setOutputDir(new File(args[1]));
		documenter.setHttp(args.length>2 ? "http".equals(args[2]) : false);
		documenter.execute();
	}

	private static void mapDiagram(EObject next) {
		if (next instanceof Diagram) {
			Diagram diagram = (Diagram) next;
			EObject diagramElement = diagram.getElement();
			if (diagramElement!=null) {
				List<Diagram> diagrams = diagramMap.get(diagramElement);
				if (diagrams == null) {
					diagrams = new ArrayList<Diagram>();
					diagramMap.put(diagramElement, diagrams);
				}
				diagrams.add(diagram);					
			}					
		}
	}
		
}
