package com.sun.identity.saml2.protocol.impl;

import com.sun.identity.saml2.common.SAML2Exception;
import com.sun.identity.saml2.protocol.NewEncryptedID;
import com.sun.identity.saml2.protocol.NewID;
import com.sun.identity.saml2.protocol.ProtocolFactory;
import com.sun.identity.saml2.xmlenc.EncManager;
import com.sun.identity.shared.xml.XMLUtils;
import java.security.Key;
import org.w3c.dom.Element;

public class NewIDImpl implements NewID {
   private static final String ELEMENT_NAME = "NewID";
   private String newID;

   public NewIDImpl(Element element) {
      this.parseElement(element);
   }

   @Override
   public String getValue() {
      return this.newID;
   }

   @Override
   public String toXMLString() throws SAML2Exception {
      return this.toXMLString(true, false);
   }

   @Override
   public String toXMLString(boolean includeNSPrefix, boolean declareNS) throws SAML2Exception {
      StringBuilder xml = new StringBuilder();
      if (this.newID != null && !this.newID.isEmpty()) {
         String ns = "";
         String nsp = "";
         if (declareNS) {
            ns = " xmlns:samlp=\"urn:oasis:names:tc:SAML:2.0:protocol\"";
         }

         if (includeNSPrefix) {
            nsp = "samlp:";
         }

         xml.append("<").append(nsp).append("NewID");
         xml.append(ns).append(">");
         xml.append(this.newID);
         xml.append("</").append(nsp).append("NewID").append(">");
      }

      return xml.toString();
   }

   @Override
   public NewEncryptedID encrypt(Key recipientPublicKey, String dataEncAlgorithm, int dataEncStrength, String recipientEntityID) throws SAML2Exception {
      Element el = EncManager.getEncInstance()
         .encrypt(this.toXMLString(true, true), recipientPublicKey, dataEncAlgorithm, dataEncStrength, recipientEntityID, "NewEncryptedID");
      return ProtocolFactory.getInstance().createNewEncryptedID(el);
   }

   void parseElement(Element element) {
      this.newID = XMLUtils.getValueOfValueNode(element);
   }
}
