
//import java.util.logging.Logger;
import java.io.PrintWriter;



public final class XmlSerializer
{
   //private static final Logger LOGGER = Logger.getLogger(ServletCutout.class.getName());

   private XmlSerializer() {} // disables instatiation

   public static void serializeToVoTable(PrintWriter writer, String charEncoding, SearchOutputData searchOutputData,
         boolean showDuration, long startTime_msec)
   {
      writer.println("<?xml version=\"1.0\" encoding=\"" + charEncoding + "\" standalone=\"yes\"?>");
      writer.println("<results>");
      writer.println("<description> TBD: VOTable " + searchOutputData.description + " </description>");
      serialize(writer, searchOutputData.inputs);
      writer.println("<msg> " + searchOutputData.versionString + " </msg>");
      writer.println("<DatacubeCount> " + searchOutputData.datacubeCount + " </DatacubeCount>");
      for(Subsurvey subsurvey : searchOutputData.subsurveyArr)
      {
         serialize(writer, subsurvey);
      }
      if(showDuration)
         writer.println("<duration unit=\"msec\">" + (System.currentTimeMillis() - startTime_msec) + "</duration>");
      writer.println("</results>");
   }


   public static void serializeToLegacyResults(PrintWriter writer, String charEncoding, SearchOutputData searchOutputData,
         boolean showDuration, long startTime_msec)
   {
      writer.println("<?xml version=\"1.0\" encoding=\"" + charEncoding + "\" standalone=\"yes\"?>");
      writer.println("<results>");
      writer.println("<description> " + searchOutputData.description + " </description>");
      serialize(writer, searchOutputData.inputs);
      writer.println("<msg> " + searchOutputData.versionString + " </msg>");
      writer.println("<DatacubeCount> " + searchOutputData.datacubeCount + " </DatacubeCount>");
      for(Subsurvey subsurvey : searchOutputData.subsurveyArr)
      {
         serialize(writer, subsurvey);
      }
      if(showDuration)
         writer.println("<duration unit=\"msec\">" + (System.currentTimeMillis() - startTime_msec) + "</duration>");
      writer.println("</results>");
   }

   public static String serialize(Coord coord)
   {
      StringBuilder xml = new StringBuilder();
      xml.append("<SkySystem>"+coord.skySystem+"</SkySystem>");
      xml.append("<l>"+coord.lon+"</l>");
      xml.append("<b>"+coord.lat+"</b>");
      switch(coord.shape)
      {
         case "CIRCLE" :  xml.append("<r>"+String.valueOf(coord.radius)+"</r>"); break;
         case "RECT"   :
                          xml.append("<dl>"+String.valueOf(coord.dlon)+"</dl>");
                          xml.append("<db>"+String.valueOf(coord.dlat)+"</db>");
                          break;
         default:
                          xml.append("<shape> unknown shape: "+ coord.shape +" </shape>");
      }
      if(coord.vel_valid)
      {
         xml.append("<vl>"   + String.valueOf(coord.vel_low)  +"</vl>");
         xml.append("<vu>"   + String.valueOf(coord.vel_up)   +"</vu>");
         xml.append("<vtype>"+ coord.vel_type                 +"</vtype>");
      }
      return xml.toString();
   }

   public static String serialize(SubsurveyId subsurveyId)
   {
      StringBuilder xml = new StringBuilder();
      if(subsurveyId.surveyName  != null) xml.append("<SurveyName>"+subsurveyId.surveyName+"</SurveyName>");
      if(subsurveyId.species     != null) xml.append("<Species>"+subsurveyId.species+"</Species>");
      if(subsurveyId.transition  != null) xml.append("<Transition>"+subsurveyId.transition+"</Transition>");
      return xml.toString();
   }

   public static String serialize(AuthPolicy auth)
   {
      StringBuilder xml = new StringBuilder();
      xml.append("<AccessPolicy>" + auth.getAccessPolicy() + "</AccessPolicy>");
      String ug = auth.getUserGroupsAsString(" ");
      if(auth.getUserName() != null) xml.append("<UserName>" + auth.getUserName() + "</UserName>");
      if(ug            != null) xml.append("<GroupNames>" + ug + "</GroupNames>");
      return xml.toString();
   }


   public static void serialize(PrintWriter writer, Inputs inputs)
   {
      writer.println("<input>");
      if(inputs.subsurveyId   != null) writer.println(serialize(inputs.subsurveyId));
      if(inputs.coord       != null) writer.println(serialize(inputs.coord));
      if(inputs.countNullValues)     writer.println("<nullvals> set </nullvals>");
      if(inputs.auth        != null) writer.println(serialize(inputs.auth));
      writer.println("</input>");
   }

   public static void serialize(PrintWriter writer, Subsurvey subsurvey)
   {
      writer.println("<survey>");
      // replace with escape the XML-predefined entities:
      // <, >, &, %
      if(subsurvey.description != null)
      {
         subsurvey.description = subsurvey.description.replace("&","&amp;");
         subsurvey.description = subsurvey.description.replace("<","&lt;");
         subsurvey.description = subsurvey.description.replace(">","&gt;");
         subsurvey.description = subsurvey.description.replace("%","&#37;");
      }

      writer.println("<Description>"  + subsurvey.description + "</Description>");
      writer.println("<Survey>"       + subsurvey.surveyname  + "</Survey>");
      writer.println("<Species>"      + subsurvey.species     + "</Species>");
      writer.println("<Transition>"   + subsurvey.transition  + "</Transition>");
      writer.println("<RestFreq>");
      writer.println("<value>"        + subsurvey.rf + "</value>");
      writer.println("<unit>"         + "Hz"             + "</unit>"); // FIXME why was this needed? checj survey_populate,csv
      writer.println("</RestFreq>");
      writer.println("<VelocityUnit>" + subsurvey.vel_unit + "</VelocityUnit>");

      for(Dataset dataset : subsurvey.datasetArr)
      {
         writer.println(serialize(dataset));
      }
      writer.println("</survey>");
   }

   public static String serialize(Dataset.Access access)
   {
      StringBuilder xml = new StringBuilder();

      xml.append("<Access>");

      if(access.accessFileUrl != null)
         xml.append("<URL type=\"file\">" + access.accessFileUrl + "</URL>");

      if(access.accessCutoutUrl != null)
         xml.append("<URL type=\"cutout\">" + access.accessCutoutUrl + "</URL>");

      if(access.accessMosaicUrl != null)
         xml.append("<URL type=\"mosaic\">" + access.accessMosaicUrl + "</URL>");

      xml.append("</Access>");

      return xml.toString();
   }

   public static String serialize(Dataset.Vertices vertices)
   {
      StringBuilder xml = new StringBuilder();
      xml.append("<vertices>");
      xml.append("<SkyCoordSystem>");
      for(int ix = 0; ix < vertices.VERT_COUNT; ix++)
      {
         xml.append("<P" + (ix+1) + ">");
         xml.append("<longitude>" + vertices.lon[ix] + "</longitude>");
         xml.append("<latitude>"  + vertices.lat[ix] + "</latitude>");
         xml.append("</P" + (ix+1) + ">");
      }
      xml.append("</SkyCoordSystem>");
      xml.append("</vertices>");

      return xml.toString();
   }


   public static String serialize(Dataset dataset)
   {
      StringBuilder xml = new StringBuilder();

      xml.append("<datacube>");
      xml.append(serializeOverlapCode("overlap", dataset.overlapCode));
      if(dataset.overlapCodeSky > 0)
      {
         xml.append(serializeOverlapCode("overlapSky", dataset.overlapCodeSky));
      }
      if(dataset.overlapCodeVel > 0)
      {
         xml.append(serializeOverlapCode("overlapVelocity", dataset.overlapCodeVel));
      }
      xml.append("<DataType>" + dataset.dataType + "</DataType>");
      xml.append("<PublisherDID>" + dataset.publisherDid + "</PublisherDID>");
      xml.append(serialize(dataset.access));
      xml.append(serialize(dataset.vertices_deg));
      xml.append("</datacube>");

      return xml.toString();
   }


   public static String serializeOverlapCode(String tagName, int ovCode)
   {
      final String[] overString =
      {
         "The check could not be performed because the input Region could not be mapped into the coordinate system of the datacube Region.",
         "There is no overlap between the two Regions.",
         "The datacube Region is completely inside the input Region.",
         "The input Region is completely inside the datacube Region.",
         "There is partial overlap between the two Regions.",
         "The Regions are identical to within their uncertainties.",
         "The input Region is the exact negation of the datacube Region to within their uncertainties."
      };

      StringBuilder xml = new StringBuilder();
      xml.append("<" + tagName + ">");
      xml.append("<description>" + ( ((ovCode>=0) && (ovCode<=6)) ? overString[ovCode] : (" ovCode out-of-range: "+ Integer.toString(ovCode)) ) + "</description>");
      xml.append("<code>"        + ovCode             + "</code>");
      xml.append("</" + tagName + ">");
      return xml.toString();
   }


}
