/***
 * Excerpted from "Domain-Driven Design Using Naked Objects",
 * published by The Pragmatic Bookshelf.
 * Copyrights apply to this code. It may not be used to create training material, 
 * courses, books, articles, and the like. Contact us if you are in doubt.
 * We make no guarantees that this code is fit for any purpose. 
 * Visit http://www.pragmaticprogrammer.com/titles/dhnako for more book information.
***/
package com.pragprog.dhnako.carserv.nakedobjects.domainservices;

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

import javax.xml.transform.TransformerConfigurationException;

import org.nakedobjects.applib.AbstractService;
import org.nakedobjects.applib.snapshot.Snapshottable;
import org.nakedobjects.runtime.snapshot.DomSerializer;
import org.nakedobjects.runtime.snapshot.DomSerializerJaxp;
import org.nakedobjects.runtime.snapshot.XmlSnapshot;
import org.w3c.dom.Document;

import com.pragprog.dhnako.carserv.dom.domainservices.SnapShotService;
import com.pragprog.dhnako.carserv.dom.domainservices.ViewXmlService;

public class SnapShotServiceImpl extends AbstractService implements SnapShotService {

	private ViewXmlService viewXmlService;
	private int fileNum;

	public void takeSnapshot(Snapshottable snapshottable) throws Exception {
		XmlSnapshot xmlSnapshot = createSnapshot(snapshottable);
		viewSnapshot(xmlSnapshot.getXmlDocument());
	}

	public void takeSnapshotXsd(Snapshottable snapshottable) throws Exception {
		XmlSnapshot xmlSnapshot = createSnapshot(snapshottable);
		viewSnapshot(xmlSnapshot.getXsdDocument());
	}

	private XmlSnapshot createSnapshot(Snapshottable snapshottable) {
		return XmlSnapshot.create(snapshottable).build();
	}
	
	private void viewSnapshot(Document xmlDoc) throws IOException,
			TransformerConfigurationException, Exception {
		File tempFile = File.createTempFile(nextFileName(), ".xml");
		tempFile.deleteOnExit();
		BufferedWriter tempFileWriter = new BufferedWriter(new FileWriter(tempFile));
		try {
			DomSerializer domSerializer = new DomSerializerJaxp();
			domSerializer.serializeTo(xmlDoc.getDocumentElement(), tempFileWriter);
			String canonicalPath = tempFile.getCanonicalPath();
			viewXmlService.viewXml(canonicalPath);
		} finally {
			tempFileWriter.close();
		}
	}

	private String nextFileName() {
		return getClassName() + (fileNum++);
	}
	
	/////////////////////////////////////////////////////////
	// Dependencies (injected)
	/////////////////////////////////////////////////////////

	public void setViewXmlService(ViewXmlService viewXmlService) {
		this.viewXmlService = viewXmlService;
	}

	
}
