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

import com.sun.identity.saml2.common.SAML2Exception;
import com.sun.identity.saml2.common.SAML2SDKUtils;
import com.sun.identity.saml2.protocol.StatusDetail;
import com.sun.identity.shared.xml.XMLUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class StatusDetailImpl implements StatusDetail {
   private boolean isMutable;
   private List<String> statusDetailList;

   public StatusDetailImpl() {
      this.isMutable = true;
   }

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

   @Override
   public void setAny(List<String> value) throws SAML2Exception {
      if (this.isMutable) {
         this.statusDetailList = value;
      } else {
         throw new SAML2Exception(SAML2SDKUtils.BUNDLE.getString("objectImmutable"));
      }
   }

   @Override
   public List<String> getAny() {
      return this.statusDetailList;
   }

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

   @Override
   public String toXMLString(boolean includeNSPrefix, boolean declareNS) throws SAML2Exception {
      String xmlStr = null;
      if (this.statusDetailList != null && !this.statusDetailList.isEmpty()) {
         StringBuilder xmlString = new StringBuilder(500);
         xmlString.append("<");
         if (includeNSPrefix) {
            xmlString.append("samlp:");
         }

         xmlString.append("StatusDetail");
         if (declareNS) {
            xmlString.append(" xmlns:samlp=\"urn:oasis:names:tc:SAML:2.0:protocol\"");
         }

         xmlString.append(">");

         for (String sdString : this.statusDetailList) {
            xmlString.append("\n").append(sdString);
         }

         xmlString.append("\n").append("</samlp:").append("StatusDetail").append(">");
         xmlStr = xmlString.toString();
      }

      return xmlStr;
   }

   @Override
   public void makeImmutable() {
      if (this.isMutable) {
         this.isMutable = false;
      }
   }

   @Override
   public boolean isMutable() {
      return this.isMutable;
   }

   private void parseElement(Element element) {
      NodeList nList = element.getChildNodes();
      if (this.statusDetailList == null || this.statusDetailList.isEmpty()) {
         this.statusDetailList = new ArrayList<>();
      }

      if (nList != null && nList.getLength() > 0) {
         for (int i = 0; i < nList.getLength(); i++) {
            Node childNode = nList.item(i);
            if (childNode.getLocalName() != null) {
               this.statusDetailList.add(XMLUtils.print(childNode));
            }
         }

         if (this.statusDetailList != null && !this.statusDetailList.isEmpty()) {
            this.statusDetailList = Collections.unmodifiableList(this.statusDetailList);
         }
      }
   }
}
