package net.ihe.xcpd.init.assertion;

import net.ihe.gazelle.simulator.common.model.ApplicationConfiguration;
import net.ihe.gazelle.simulator.common.utils.XmlUtil;
import net.ihe.gazelle.simulator.common.xua.SamlAssertionAttributes;
import net.ihe.gazelle.simulator.common.xua.SamlAssertionSupplier;
import net.ihe.gazelle.simulator.common.xua.SamlSampleAssertionAttributes;
import net.ihe.gazelle.simulator.common.xua.SignatureException;
import net.ihe.gazelle.simulator.common.xua.SignatureUtil;
import net.ihe.xcpd.init.tools.XmlFormatter;

import org.picketlink.identity.federation.core.wstrust.WSTrustException;
import org.w3c.dom.Element;

/**
 * @author abderrazek boufahja
 */
public class AssertionGenerator {

    public static String asser = "<Assertion xmlns=\"urn:oasis:names:tc:SAML:2.0:assertion\" xmlns:ns2=\"http://www.w3.org/2001/04/xmlenc#\" xmlns:ns3=\"http://www.w3.org/2000/09/xmldsig#\" ID=\"ID_901b2767-ed9f-4056-b6eb-a580a3bb6d4d\" IssueInstant=\"2010-09-22T14:12:12.616Z\" Version=\"2.0\"><Issuer>PicketLinkSTS</Issuer><Subject><NameID NameQualifier=\"urn:picketlink:identity-federation\">ANONYMOUS</NameID><SubjectConfirmation Method=\"urn:oasis:names:tc:SAML:2.0:cm:bearer\"/></Subject><Conditions NotBefore=\"2010-09-22T14:12:12.616Z\" NotOnOrAfter=\"2010-09-22T16:12:12.616Z\"/><dsig:Signature xmlns:dsig=\"http://www.w3.org/2000/09/xmldsig#\"><dsig:SignedInfo><dsig:CanonicalizationMethod Algorithm=\"http://www.w3.org/2001/10/xml-exc-c14n#WithComments\"/><dsig:SignatureMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#rsa-sha1\"/><dsig:Reference URI=\"#ID_901b2767-ed9f-4056-b6eb-a580a3bb6d4d\"><dsig:Transforms><dsig:Transform Algorithm=\"http://www.w3.org/2000/09/xmldsig#enveloped-signature\"/><dsig:Transform Algorithm=\"http://www.w3.org/2001/10/xml-exc-c14n#\"/></dsig:Transforms><dsig:DigestMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#sha1\"/><dsig:DigestValue>CVPvN0L2tVVdpSFvmGd5RC+fSqI=</dsig:DigestValue></dsig:Reference></dsig:SignedInfo><dsig:SignatureValue>eKn89KfwN78/fEQQYaXyZ8JG/WP8F3pcG4jKsXIvJBT7qT0N3IFce49NrsgImE0St/crs/619sk4" +
    "IRkAwKL0bguVud8P5CfOAkmZy2/oJKorj5LTJdezZ/vKhRP7fSWdOlItU5HnwrBudWpZ3a7A4Z4V" +
    "qpn7YdS+gfCpHQAgZe0=</dsig:SignatureValue><dsig:KeyInfo><dsig:KeyValue><dsig:RSAKeyValue><dsig:Modulus>suGIyhVTbFvDwZdx8Av62zmP+aGOlsBN8WUE3eEEcDtOIZgO78SImMQGwB2C0eIVMhiLRzVPqoW1" +
    "dCPAveTm653zHOmubaps1fY0lLJDSZbTbhjeYhoQmmaBro/tDpVw5lKJns2qVnMuRK19ju2dxpKw" +
    "lYGGtrP5VQv00dfNPbs=</dsig:Modulus><dsig:Exponent>AQAB</dsig:Exponent></dsig:RSAKeyValue></dsig:KeyValue></dsig:KeyInfo></dsig:Signature></Assertion>";

    public static String generateToken(String nameHCPID, String patientId) throws Exception{
        String pathass = ApplicationConfiguration.getValueOfVariable("path_ass_keystore");
        SignatureUtil signatureUtil = new SignatureUtil(pathass + "simu.jks", "gazelle", "tomcat", "gazelle");

        SamlAssertionAttributes attributesIdentity = new SamlAssertionAttributes(false);

        attributesIdentity.setXSPARole("medical doctor");
        attributesIdentity.setXSPAPurposeOfUse("TREATMENT");
        attributesIdentity.setXSPASubject("Dr. Muller");
        attributesIdentity.setXSPAOrganization("Vienna AKH");
        attributesIdentity.setXSPAOrganizationId("urn:oid:1.2.3.4.5.6.7");
        // use default HL7 permissions

        attributesIdentity.setEpSOSHealthcareFacilityType("Resident Physician");

        attributesIdentity.setXSPALocality("vienna-akh");
        attributesIdentity.setHITSPClinicalSpeciality("UNKNOWN");

        Element identityElement =  SamlAssertionSupplier.getAssertion(nameHCPID, attributesIdentity , signatureUtil);
        String identityStr = XmlUtil.outputDOM(identityElement);

        SamlAssertionAttributes attributesTRC = new SamlAssertionAttributes(true);
        attributesTRC.setXSPASubjectTRC(patientId);
        attributesTRC.setXSPAPurposeOfUse("TREATMENT");
        Element trcElement =  SamlAssertionSupplier.getAssertionTRC(nameHCPID, attributesTRC, identityElement, signatureUtil);
        String trcStr = XmlUtil.outputDOM(trcElement);
        
        return identityStr + trcStr;
    }
    //*/

    @Deprecated
    public static String generateAssertionFromAttributes(String role, String purposeOfUse,
            String subject, String organization,
            String organizationId, String permissionsHL7,
            String healthcareFacilityType, String locality, String nameHCPID) throws WSTrustException, SignatureException{

        String pathass = ApplicationConfiguration.getValueOfVariable("path_ass_keystore");
        SignatureUtil signatureUtil = new SignatureUtil(pathass + "simu.jks", "gazelle", "tomcat", "gazelle");

        SamlAssertionAttributes attributes = new SamlAssertionAttributes(false);

        attributes.setXSPARole(role);
        attributes.setXSPAPurposeOfUse(purposeOfUse);
        attributes.setXSPASubject(subject);
        attributes.setXSPAOrganization(organization);
        attributes.setXSPAOrganizationId(organizationId);
        attributes.getXSPAPermissionsHL7().clear();
        attributes.getXSPAPermissionsHL7().add(permissionsHL7);

        attributes.setEpSOSHealthcareFacilityType(healthcareFacilityType);

        attributes.setXSPALocality(locality);
        attributes.setHITSPClinicalSpeciality("UNKNOWN");

        Element e =  SamlAssertionSupplier.getAssertion(nameHCPID, attributes , signatureUtil);
        String res = XmlUtil.outputDOM(e);
        return res;
    }


    /*
    public static String generateToken(String STSurl, String nameHCPID) throws Exception{
        SamlAssertionSupplierDOM provider = new SamlAssertionSupplierDOM();
        configureActor(provider, STSurl);
        String res = null;
        try {
            SamlAssertionAttributes attributes = getAttributes();
            System.out.println("attributes = " + attributes.getXSPASubject());
            Element assertion = provider.getAssertion(nameHCPID, attributes);
            res = ElementString.printAssertion(assertion);
        } catch (WSTrustException e) {
            throw new RuntimeException(e);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }
    //*/

    private static SamlAssertionAttributes getAttributes() {
        SamlAssertionAttributes attributes = new SamlAssertionAttributes(false);
        attributes.setXSPASubject("Dr. Muller");
        attributes.setXSPAOrganization("Vienna AKH");
        attributes.setXSPAOrganizationId("urn:oid:1.2.3.4.5.6.7");
        attributes.setEpSOSHealthcareFacilityType("Resident Physician");
        // attributes.setHITSPClinicalSpeciality("???");
        attributes.setXSPARole("Physician");
        attributes.setXSPALocality("vienna-akh");
        attributes.setXSPAPurposeOfUse("TREATMENT");

        attributes.getXSPAPermissionsHL7().add("urn:oasis:names:tc:xspa:1.0:hl7:PRD-006");
        attributes.getXSPAPermissionsHL7().add("urn:oasis:names:tc:xspa:1.0:hl7:PRD-017");
        attributes.getXSPAPermissionsHL7().add("urn:oasis:names:tc:xspa:1.0:hl7:PRD-010");
        return attributes;
    }

    public static void main(String[] args) throws Exception {
        String res = generateToken("http://gazelle.ihe.net/sts" , "HCPXX");
        //res = XmlFormatter.prettyFormat(res, 0);
        System.out.println("res = " + res);
    }

}
