package info.bukova.isspst.reporting;

import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.PdfFormField;
import com.lowagie.text.pdf.PdfName;
import net.sf.jasperreports.engine.JRGenericPrintElement;
import net.sf.jasperreports.engine.JRPropertiesMap;
import net.sf.jasperreports.engine.export.GenericElementHandler;
import net.sf.jasperreports.engine.export.GenericElementHandlerBundle;
import net.sf.jasperreports.engine.export.GenericElementPdfHandler;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.export.JRPdfExporterContext;
import net.sf.jasperreports.extensions.ExtensionsRegistry;
import net.sf.jasperreports.extensions.ExtensionsRegistryFactory;
import net.sf.jasperreports.extensions.SingletonExtensionRegistry;

/**
 * @author Pepa Rokos
 */
public class SignaturePdfHandler implements GenericElementPdfHandler, GenericElementHandlerBundle, ExtensionsRegistryFactory {

	@Override
	public ExtensionsRegistry createRegistry(String registryId, JRPropertiesMap properties) {
		return new SingletonExtensionRegistry<GenericElementHandlerBundle>(GenericElementHandlerBundle.class, this);
	}

	@Override
	public void exportElement(JRPdfExporterContext exporterContext, JRGenericPrintElement element) {
		//PdfFormField field = PdfFormField.createSignature(exporterContext.getPdfWriter());
		PdfFormField field = PdfFormField.createTextField(exporterContext.getPdfWriter(), true, false, 255);
		Object param = element.getParameterValue("index");
		String index = param != null ? String.valueOf(param) : null;

		if (index != null) {
			field.setFieldName("signature-" + index);
		} else {
			field.setFieldName("signature");
		}

		field.put(PdfName.V, exporterContext.getPdfWriter().getPdfIndirectReference());
		field.setFieldFlags(PdfFormField.FF_READ_ONLY);

		field.setWidget(new Rectangle(element.getX(),
				exporterContext.getExportedReport().getPageHeight() - element.getY(),
				element.getX() + element.getWidth(),
				exporterContext.getExportedReport().getPageHeight() - element.getY() - element.getHeight()), PdfName.HIGHLIGHT);
		exporterContext.getPdfWriter().addAnnotation(field);
	}

	@Override
	public boolean toExport(JRGenericPrintElement element) {
		return true;
	}

	@Override
	public String getNamespace() {
		return "urn:sig:sig";
	}

	@Override
	public GenericElementHandler getHandler(String elementName, String exporterKey) {
		if (elementName.equals("signature") && exporterKey.equals(JRPdfExporter.PDF_EXPORTER_KEY)) {
			return this;
		}

		return null;
	}
}
