package lu.tudor.santec.gecamed.formeditor.gui.controller.converter;

import java.awt.Desktop;
import java.io.File;
import java.io.IOException;

import lu.tudor.santec.gecamed.core.ejb.entity.beans.XSLTemplate;
import lu.tudor.santec.gecamed.core.gui.controller.document.writer.WriterController;
import lu.tudor.santec.gecamed.core.utils.controller.utils.FileUtils;
import lu.tudor.santec.gecamed.formeditor.gui.model.FormModel;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.jdom.JDOMException;

public class DesktopFormDataConverter extends FormDataConverter
{
	/** the logger Object for this class */
	private static Logger logger = Logger.getLogger(DesktopFormDataConverter.class.getName());
	
	/* ======================================== */
	// 		MEMBERS
	/* ======================================== */
	
	private Desktop desktop;
	
	
	
	/* ======================================== */
	// 		CONSTRUCTOR
	/* ======================================== */
	
	protected DesktopFormDataConverter(FormModel model)
	{
		super(model);
		desktop = Desktop.getDesktop();
	}
	
	
	protected File createFile (boolean edit, XSLTemplate xslTemplate) throws JDOMException, IOException
	{
		String 		type 		= edit ? TYPE_EDIT : TYPE_PRINT;
//		XSLTemplate xslTemplate = getXslTemplate(type);
		byte[] 		fileData;
		File 		file;
		
		fileData = createFileData(type, xslTemplate);
		
		// the dialog was cancelled and therefore html is null
		if (fileData == null)
			return null;
		
		file = File.createTempFile(WriterController.DOCUMENT_NAME, "."+xslTemplate.getFileNameExtension());
		file = FileUtils.createFile(fileData, file);
		
		return file;
	}
	
	
	
	/* ======================================== */
	// 		OVERRIDDEN METHODS
	/* ======================================== */
	
	@Override
	public void edit(XSLTemplate xslTemplate)
	{
		try
		{
			File file = createFile(true, xslTemplate);
			if (file != null)
				desktop.edit(file);
		}
		catch (Exception e)
		{
			logger.log(Level.WARN, e.getMessage(), e);
		}
	}
	
	
	@Override
	public void open(XSLTemplate xslTemplate)
	{
		try
		{
			File file = createFile(true, xslTemplate);
			if (file != null)
				desktop.open(file);
		}
		catch (JDOMException e)
		{
			// the error message is already shown just throw the warning ...
			logger.log(Level.WARN, e.getMessage(), e);
		}
		catch (IOException e)
		{
			logger.log(Level.ERROR, e.getMessage(), e);
		}
	}
	

	@Override
	public void print(XSLTemplate xslTemplate)
	{
		try
		{
			File file = createFile(false, xslTemplate);
			if (file != null)
				desktop.print(file);
		}  
		catch (JDOMException e)
		{
			// the error message is already shown and the warning thrown ...
			logger.log(Level.WARN, e.getMessage(), e);
		}
		catch (IOException e)
		{
			logger.log(Level.ERROR, e.getMessage(), e);
		}
	}
}
