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

import lu.tudor.santec.gecamed.core.ejb.entity.beans.XSLTemplate;
import lu.tudor.santec.gecamed.core.gui.controller.document.DocumentController;
import lu.tudor.santec.gecamed.core.gui.controller.document.UnsupportedFileTypeException;
import lu.tudor.santec.gecamed.formeditor.gui.model.FormModel;

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

public class DocumentFormDataConverter extends FormDataConverter
{
	/* ======================================== */
	// 		CONSTANTS
	/* ======================================== */
	
	/** the logger Object for this class */
	private static Logger logger = Logger.getLogger(DocumentFormDataConverter.class.getName());
	
	
	
	/* ======================================== */
	// 		MEMBERS
	/* ======================================== */
	
	private DocumentController controller;
	
	
	
	/* ======================================== */
	// 		CONSTRUCTOR
	/* ======================================== */
	
	protected DocumentFormDataConverter(FormModel model, DocumentController controller)
	{
		super(model);
		this.controller = controller;
	}

	
	
	/* ======================================== */
	// 		OVERRIDDEN METHODS
	/* ======================================== */
	
	private boolean open (boolean hidden, XSLTemplate xslTemplate) throws UnsupportedFileTypeException
	{
		byte[] 		data 		= null;
		String 		type 		= hidden ? TYPE_PRINT : TYPE_EDIT;
//		XSLTemplate xslTemplate = getXslTemplate(type);
		
		if (xslTemplate == null)
			return false;
		
		try
		{
			data = createFileData(type, xslTemplate);
		}
		catch (Exception e)
		{
			logger.log(Level.WARN, e.getMessage());
		}
		
		if (data == null)
			return false;
		
		try
		{
			controller.setDocument(data);
			controller.open(DocumentController.TYPE_OTHER, hidden);
			return true;
		}
		catch (UnsupportedFileTypeException e)
		{
			throw e;
		}
		catch (Exception e)
		{
			logger.log(Level.ERROR, e.getMessage(), e);
			controller.closeAndDeleteFile();
			return false;
		}
	}
	
	
	@Override
	public void edit (XSLTemplate xslTemplate)
	{
		open(false, xslTemplate);
	}
	
	
	public void open (XSLTemplate xslTemplate)
	{
		open(false, xslTemplate);
	}
	
	
	@Override
	public void print (XSLTemplate xslTemplate)
	{
		if (open(true, xslTemplate))
			controller.print();
	}
}
