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

import org.apache.axis.client.Stub;
import org.apache.axis.encoding.Base64;
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;

/**
 * CMS/PKCS#7 Signature Generation
 * 
 * @author aalcaide
 */
public class CreateSignature_CAdES_BES_Detached_BigFile {

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

	private static final String filename = "demo-file-BigFile.pdf";
	

	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);
			
			// Text Signature (CMS)
			ssr.setProfile(Constants.Profile.CMSPKCS7);
			
			// Referčncia al fitxer que conté les dades a signar
			// Parŕmetres: path (codificat en Base64) del fitxer + tipus de dades del fitxer (Raw o Base64) 
			ssr.setInputBase64DataFile(Base64.encode((path_in+filename).getBytes()), Constants.SourceFormat.RAW);
			
			// CMS signature type
			ssr.setSignatureType(Constants.SignatureType.CADES);
			// CAdES signature form
			ssr.setSignatureFormat(Constants.SignatureFormat.BES);

			// Key selection using Distinguished Name			
			ssr.setKeySubjectName(distinguishedName);
			
			// 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("."))
						+ "_Signature_CAdES_BES_Detached.p7b";
				Util.writeBinaryFileB64(destFilename, ssrs.getSignatureBase64());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}