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

import com.sun.identity.saml2.assertion.AssertionFactory;
import com.sun.identity.saml2.assertion.EncryptedID;
import com.sun.identity.saml2.assertion.NameID;
import com.sun.identity.saml2.common.SAML2Exception;
import com.sun.identity.saml2.common.SAML2SDKUtils;
import com.sun.identity.saml2.xmlenc.EncManager;
import com.sun.identity.shared.xml.XMLUtils;
import java.security.Key;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class EncryptedIDImpl extends EncryptedElementImpl implements EncryptedID {
   private static final String ELEMENT_NAME = "EncryptedID";

   private void parseElement(Element element) throws SAML2Exception {
      if (element == null) {
         if (SAML2SDKUtils.DEBUG.messageEnabled()) {
            SAML2SDKUtils.DEBUG.message("EncryptedIDImpl.parseElement: Input is null.");
         }

         throw new SAML2Exception(SAML2SDKUtils.BUNDLE.getString("nullInput"));
      } else {
         String tag = null;
         tag = element.getLocalName();
         if (tag == null || !tag.equals("EncryptedID")) {
            if (SAML2SDKUtils.DEBUG.messageEnabled()) {
               SAML2SDKUtils.DEBUG.message("EncryptedIDImpl.parseElement: not EncryptedIDImpl.");
            }

            throw new SAML2Exception(SAML2SDKUtils.BUNDLE.getString("wrongInput"));
         }
      }
   }

   public EncryptedIDImpl(Element element) throws SAML2Exception {
      this.parseElement(element);
      this.xmlString = XMLUtils.print(element);
   }

   public EncryptedIDImpl(String xmlString) throws SAML2Exception {
      Document doc = XMLUtils.toDOMDocument(xmlString, SAML2SDKUtils.DEBUG);
      if (doc == null) {
         throw new SAML2Exception(SAML2SDKUtils.BUNDLE.getString("errorObtainingElement"));
      }

      this.parseElement(doc.getDocumentElement());
      this.xmlString = xmlString;
   }

   @Override
   public NameID decrypt(Key recipientPrivateKey) throws SAML2Exception {
      Element el = EncManager.getEncInstance().decrypt(this.xmlString, recipientPrivateKey);
      return AssertionFactory.getInstance().createNameID(el);
   }
}
