package de.tu_dresden.diplom.richter_mirko_mat2628335.uddipopulation;

import org.apache.log4j.Logger;
import org.systinet.uddi.client.v3.struct.*;
import org.systinet.uddi.client.v3.UDDI_Inquiry_PortType;
import org.systinet.uddi.client.v3.UDDIException;
import org.systinet.uddi.client.base.StringArrayList;
import org.systinet.uddi.InvalidParameterException;

import javax.xml.soap.SOAPException;
import java.util.Iterator;

import de.tu_dresden.diplom.richter_mirko_mat2628335.uddipopulation.businessDiplCoop.DiplomaCooperation;

/**
 * Class that is used to print the created structure to Logging-mechanism to validate
 * that the structure has been created.
 */
public class UDDIStructurePrinter extends Base {

   private static final Logger logger = Logger.getLogger(UDDIStructurePrinter.class);

   /**
    * Convinient method to print the structure.
    */
   public void printStructure() {
      //printTModels("diplom%", "approximateMatch", 10);
      printBusinesses(DiplomaCooperation.BUSINESS_DIPLOMA_COOP_KEY, "approximateMatch", 10);
      printBindings();
   }

   /**
    * Prints the bindingTemplates to Log4J.
    */
   private void printBindings(){
      final String fn = "[printBindings] ";
      try {
         Find_binding find_binding = new Find_binding();
         find_binding.setServiceKey(DiplomaCooperation.WITNESS_SERVICE_KEY);
         find_binding.setTModelKeyArrayList(new StringArrayList(Base.CERTIFICATE_TAXONOMY_TMODEL_KEY));
         //find_binding.setTModelKeyArrayList(new StringArrayList("uddi:notExistent"));
         UDDI_Inquiry_PortType inquiry = getInquiryStub();
         if (logger.isDebugEnabled()) logger.debug(fn + "Search in progress ...");
         BindingDetail bindingDetail = inquiry.find_binding(find_binding);
         printBindingList(bindingDetail);

         // Print the ticket-service
         find_binding = new Find_binding();
         find_binding.setServiceKey(DiplomaCooperation.TICKET_SERVICE_KEY);
         find_binding.setTModelKeyArrayList(new StringArrayList(Base.CERTIFICATE_TAXONOMY_TMODEL_KEY));
         inquiry = getInquiryStub();
         if (logger.isDebugEnabled()) logger.debug(fn + "Search in progress ...");
         bindingDetail = inquiry.find_binding(find_binding);
         printBindingList(bindingDetail);
      } catch (InvalidParameterException e) {
         e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
      } catch (SOAPException e) {
         e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
      } catch (UDDIException e) {
         e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
      }
   }

   /**
    * Prints our business DIPLOMA COOPERATION to Log4J.
    * @param tModelName name of the tModel
    * @param tModelfindQualifier the find qualifier
    * @param maxRows maximum entry to print
    */
   private void printBusinesses(String tModelName, String tModelfindQualifier, int maxRows) {
      final String fn = "[printBusinesses] ";
      try {
         Find_business find_business = new Find_business();
         find_business.setAuthInfo(getAuthInfo());
         Find_tModel find_tModel = new Find_tModel();
         find_tModel.setName(new Name(tModelName));
         find_tModel.addFindQualifier(tModelfindQualifier);
         find_tModel.setMaxRows(new Integer(5));
         //find_business.setFind_tModel(find_tModel);
         find_business.setNameArrayList(new NameArrayList(new Name(DiplomaCooperation.BUSINESS_DIPLOMA_COOP_NAME)));
         find_business.setMaxRows(new Integer(maxRows));
         UDDI_Inquiry_PortType inquiry = getInquiryStub();
         if (logger.isDebugEnabled()) logger.debug(fn + "Search in progress ...");
         BusinessList businessList = inquiry.find_business(find_business);
         printBusinesses(businessList);
         if (logger.isDebugEnabled()) logger.debug(fn + "Done ...");
      } catch (SOAPException e) {
         e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
      } catch (InvalidParameterException e) {
         e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
      } catch (UDDIException e) {
         e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
      }
   }

   /**
    * Prints the tModels identified by the given name and find qualifier
    * @param name name of the tModel
    * @param findQualifier the find qulifier
    * @param maxRows maximum rows to obtain and print
    */
   private void printTModels(String name, String findQualifier, int maxRows) {
      final String fn = "[printTModels] ";
      if (logger.isDebugEnabled()) logger.debug(fn + "Searching for tModels ... name: '" + name + "'; findQualifier: '" + findQualifier + "'; maxRows: '" + maxRows + "'");
      try {
         Find_tModel find_tModel = new Find_tModel();
         find_tModel.setName(new Name(name));
         find_tModel.setMaxRows(new Integer(maxRows));
         find_tModel.addFindQualifier(findQualifier);
         UDDI_Inquiry_PortType inquiry = getInquiryStub();
         if (logger.isDebugEnabled()) logger.debug(fn + "Search in progress ...");
         TModelList tModelList = inquiry.find_tModel(find_tModel);
         printTModelList(tModelList);
         if (logger.isDebugEnabled()) logger.debug(fn + "Done ...");
      } catch (InvalidParameterException e) {
         e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
      } catch (UDDIException e) {
         e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
      } catch (SOAPException e) {
         e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
      }
   }

   /**
    * Gets the first TModelInfo from the given list.
    * @param list the result-list
    * @return the first entry
    */
   private TModelInfo getTModelInfo(TModelList list) {
      final String fn = "[getTModelInfo] ";
      TModelInfo result = null;
      TModelInfoArrayList tModelInfoArrayList = list.getTModelInfoArrayList();
      if (tModelInfoArrayList == null || tModelInfoArrayList.size() == 0) {
         if (logger.isInfoEnabled()) logger.info(fn + "Nothing found");
      } else {
         if (tModelInfoArrayList.size() > 1) {
            if (logger.isInfoEnabled()) logger.info(fn + "More than one tModel in list!");
         }
         result = tModelInfoArrayList.get(0);
      }
      return result;
   }

   /**
    * Prints the given tModel-list to Log4J
    * @param models tModels to print
    */
   private void printTModelList(TModelList models) {
      final String fn = "[printTModelList] ";
      TModelInfoArrayList tModelInfoArrayList = models.getTModelInfoArrayList();
      if (tModelInfoArrayList == null) {
         if (logger.isInfoEnabled()) logger.info(fn + "Nothing found");
      } else {
         if (logger.isDebugEnabled()) logger.debug(fn + "Printing " + tModelInfoArrayList.size() + " tModels ...");
         int position = 1;
         for (Iterator iterator = tModelInfoArrayList.iterator(); iterator.hasNext();) {
            TModelInfo tModelTemplate = (TModelInfo) iterator.next();
            if (logger.isDebugEnabled()) {
               StringBuffer result = new StringBuffer("TModel ").append(position).append(" : ").append(tModelTemplate.getTModelKey()).append(":\n");
               result.append(tModelTemplate.toXML()).append("\n");
               result.append("********************************************************");
               logger.debug(fn + result);
            }
            position++;
         }
      }
   }

   /**
    * Prints the given list of businesses to Log4J
    * @param list list of businesses to print
    * @throws InvalidParameterException
    * @throws SOAPException
    * @throws UDDIException
    */
   private void printBusinesses(BusinessList list) throws InvalidParameterException, SOAPException, UDDIException {
      final String fn = "[printBusinesses] ";
      BusinessInfoArrayList businessInfoArrayList = list.getBusinessInfoArrayList();
      if (businessInfoArrayList == null) {
         if (logger.isInfoEnabled()) logger.info(fn + "Nothing found!");
      } else {
         if (logger.isDebugEnabled()) logger.debug(fn + "Printing " + businessInfoArrayList.size() + " businesses");
         int position = 1;
         for (Iterator it = businessInfoArrayList.iterator(); it.hasNext();) {
            BusinessInfo info = (BusinessInfo) it.next();
            if (logger.isDebugEnabled()) {
               StringBuffer result = new StringBuffer("Business ").append(position).append(" : ").append(info.getBusinessKey()).append(":\n");
               result.append(info.toXML()).append("\n");
               ServiceInfoArrayList infoArrayList = info.getServiceInfoArrayList();
//               if (infoArrayList == null) {
//                  if (logger.isInfoEnabled()) logger.info(fn + "no services defined");
//               } else {
//                  for (Iterator iter = infoArrayList.iterator(); iter.hasNext();) {
//                     ServiceInfo serviceInfo = (ServiceInfo) iter.next();
//                     Find_service find_service = new Find_service();
//                     find_service.setNameArrayList(serviceInfo.getNameArrayList());
//                     UDDI_Inquiry_PortType inquiry = getInquiryStub();
//                     if (logger.isDebugEnabled()) logger.debug(fn + "Search in progress ...");
//                     ServiceList serviceList = inquiry.find_service(find_service);
//                     if (logger.isDebugEnabled()) logger.debug(fn + "Done ...");
//                     printServiceInfoArrayList(serviceList);
//                  }
//               }
               logger.debug(fn + result);
               printServiceInfoArrayList(infoArrayList);
            }
            position++;
         }
      }
   }

   /**
    * Prints the given list of ServiceInfos to Log4J
    * @param infoArrayList the list to print
    */
   private void printServiceInfoArrayList(ServiceInfoArrayList infoArrayList) {
      final String fn = "[printServiceInfoArrayList] ";
      if (infoArrayList == null) {
         if (logger.isInfoEnabled()) logger.info(fn + "Nothing found!");
      } else {
         if (logger.isDebugEnabled()) logger.debug(fn + "Printing " + infoArrayList.size() + " services");
         int position = 1;
         for (Iterator it = infoArrayList.iterator(); it.hasNext();) {
            ServiceInfo info = (ServiceInfo) it.next();
            if (logger.isDebugEnabled()) {
               StringBuffer result = new StringBuffer("Service ").append(position).append(" : ").append(info.getServiceKey()).append(":\n");
               result.append(info.toXML());
               logger.debug(fn + result);
            }
            position++;
         }
      }
   }

   /**
    * Prints the services form the given ArrayList.
    *
    * @param serviceList
    */
   private void printServiceList(ServiceList serviceList) throws InvalidParameterException, SOAPException, UDDIException {
      //final String fn = "[printServiceInfoArrayList] ";
      ServiceInfoArrayList infoArrayList = serviceList.getServiceInfoArrayList();
      printServiceInfoArrayList(infoArrayList);
   }

   /**
    * Prints the given list of bindings to Log4J
    * @param bindingDetail the detail to print
    */
   private void printBindingList(BindingDetail bindingDetail) {
      final String fn = "[printBindingList] ";
      BindingTemplateArrayList bindingArrayList = bindingDetail.getBindingTemplateArrayList();
      if(bindingArrayList == null){
         if(logger.isInfoEnabled())logger.info(fn + "Nothing found!");
      }else{
         if (logger.isDebugEnabled()) logger.debug(fn + "Printing " + bindingArrayList.size() + " bindings");
         int position = 1;
         for(Iterator it=bindingArrayList.iterator(); it.hasNext();){
            BindingTemplate bindTempl = (BindingTemplate) it.next();
            if (logger.isDebugEnabled()){
               StringBuffer result = new StringBuffer("Binding ").append(position).append(" : ").append(bindTempl.getServiceKey()).append(":\n");
               result.append(bindTempl.toXML());
               logger.debug(fn + result);
            }
            position++;
         }
      }
   }
}
