package com.chenyang.nse.bussiness.engine.infa.basic.webservice;

import com.chenyang.nse.bussiness.engine.infa.InfoProperty;
import com.chenyang.nse.bussiness.tools.xml.DocTool;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPHeaderElement;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.Dispatch;
import javax.xml.ws.Service;
import javax.xml.ws.Service.Mode;
import org.w3c.dom.Document;

public class GetAllFoldersWebService {
   public static String returnStatus(String sessionId, InfoProperty engine) throws Exception {
      String ns = engine.getWebserviceurl();
      String wsdlUrl = engine.getWebservicedataurl();
      URL url = new URL(wsdlUrl);
      QName sname = new QName(ns, "MetadataService");
      Service service = Service.create(url, sname);
      Dispatch<SOAPMessage> dispatch = service.createDispatch(new QName(ns, "Metadata"), SOAPMessage.class, Mode.MESSAGE);
      SOAPMessage msg = MessageFactory.newInstance("SOAP 1.1 Protocol").createMessage();
      SOAPEnvelope envelope = msg.getSOAPPart().getEnvelope();
      SOAPHeader head = envelope.getHeader();
      QName hename = new QName(ns, "Context", "ns0");
      SOAPHeaderElement hele = head.addHeaderElement(hename);
      hele.addChildElement("SessionId").setValue(sessionId);
      SOAPBody body = envelope.getBody();
      QName ename = new QName(ns, "GetAllFolders", "ns0");
      body.addBodyElement(ename);

      try {
         SOAPMessage response = (SOAPMessage)dispatch.invoke(msg);
         Document doc = response.getSOAPPart().getEnvelope().getBody().extractContentAsDocument();
         System.out.println(">>>>>>>GetAllFolders XML: " + DocTool.toStringFromDoc(doc));
         if (doc.getElementsByTagName("FolderInfo") == null) {
            return "FAIL";
         } else {
            StringBuffer sf = new StringBuffer();

            for(int i = 0; i < doc.getElementsByTagName("FolderInfo").getLength(); ++i) {
               if (i == 0) {
                  sf.append(doc.getElementsByTagName("Name").item(i).getTextContent());
               } else {
                  sf.append("," + doc.getElementsByTagName("Name").item(i).getTextContent());
               }
            }

            return sf.toString();
         }
      } catch (Exception e) {
         e.printStackTrace();
         return "FAIL";
      }
   }
}
