package net.catcert.trustedX.Creation.PDF.CAdES.BES;

import org.apache.axis.client.Stub;
import org.apache.axis.message.SOAPHeaderElement;
import org.apache.commons.configuration.Configuration;

import utils.TrustedXConfiguration;
import utils.Util;
import utils.UtilTrustedX;

import com.safelayer.trustedx.client.smartwrapper.Constants;
import com.safelayer.trustedx.client.smartwrapper.SmartHeader;
import com.safelayer.trustedx.client.smartwrapper.SmartSignRequest;
import com.safelayer.trustedx.client.smartwrapper.SmartSignResponse;

/**
 * PDF signature generation
 * 
 * @author aalcaide
 */
public class CreateSignaturePDF_CAdES_BES_Detached {

	private static final String path_in = "in/docs_to_sign/";
	private static final String path_out = "out/Signatures/PDF/";

	private static final String filename = "demo-file.pdf";
	
    private static final String pdfSignatureInfo = "<css:PdfSignatureInfo xmlns:css='http://www.safelayer.com/TWS'><css:PdfAttributes>"+
    											   "<css:validationMethod>PPKMS</css:validationMethod>"+
    											   "<css:signaturePosition>FIRST</css:signaturePosition>"+
    											   "<css:signatureAlg>DETACHED</css:signatureAlg>"+ //detached
    											   "</css:PdfAttributes></css:PdfSignatureInfo>";
		
	public static void main(String[] args) {
		try {

			Configuration conf = TrustedXConfiguration.getConfiguration();
			String host = conf.getString("host");
			String distinguishedName = conf.getString("distinguishedname");
			String dipositari = conf.getString("dipositari");
			String rol  = conf.getString("rol");
			
			// Definition of Signature Request endpoint
			SmartSignRequest ssr = new SmartSignRequest(host);
			
			// Add customized header elements for SOAP
			Stub stub = (Stub) ssr.getStub();
			stub.setHeader(null, "Rol", rol);
			stub.setHeader(null, "Dipositari", dipositari);

			// PDF Signature
			ssr.setProfile(Constants.Profile.PDF);
			// Read pdf file
			ssr.setInputPdfBase64Data(Util.readBinaryFileB64(path_in + filename));			
			
			// Key selection using Distinguished Name			
			ssr.setKeySubjectName(distinguishedName);
			
			// CAdES signature type
			ssr.setSignatureType(Constants.SignatureType.CADES);
			// CAdES signature form
			ssr.setSignatureFormat(Constants.SignatureFormat.BES);

			// Add PDF Signature Information
			ssr.setPdfSignatureInfo(pdfSignatureInfo);
			
			// Sending the request
			SmartSignResponse ssrs = ssr.send();

			if (UtilTrustedX.checkSW(ssrs.getResultMajor(), ssrs.getResultMinor(), ssrs.getResultMessage())) {
				// Retrieve and write signature data to disk
				String destFilename = path_out + filename.substring(0, filename.lastIndexOf("."))
						+ "_Signed_CAdES_BES_Detached.pdf";
				Util.writeBinaryFileB64(destFilename, ssrs.getDocumentWithSignaturePdf());
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
