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

// VOTable
import uk.ac.starlink.table.*;// StarTable needed
import uk.ac.starlink.votable.*;// Writer needed

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.BufferedWriter;



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

   private XmlSerializer() {} // disables instatiation


   // VOTable

   public static void serializeToVoTable(PrintWriter writer, String charEncoding, SearchOutputData searchOutputData,
         boolean showDuration, long startTime_msec) throws IOException
   {
      StarTable dstable = makeSearchResultsTable( searchOutputData.subsurveyArr );

      dstable.setParameter(new DescribedValue(new DefaultValueInfo( "subsurveyCount", Integer.class, "Count of subsurveys with found datacube(s)" ), searchOutputData.subsurveyArr.length ) );
      dstable.setParameter(new DescribedValue(new DefaultValueInfo( "datacubeCount",  Integer.class, "Count of all datacubes from VLKB-search" ), searchOutputData.datacubeCount ) );

      StarTable[] tables = {dstable};

      BufferedWriter out = new BufferedWriter( writer );

      out.write("<?xml-stylesheet type='text/xsl' href='VOTable2XHTML.xsl'?>");
      //out.write("<?xml-stylesheet type='text/xsl' href='http://www.ivoa.net/internal/IVOA/VOTableSoftware/VOTable2XHTML.xsl'?>");
      out.write( "<VOTABLE version='1.1'>\n" );
      out.write( "<RESOURCE>\n" );
      out.write( "<DESCRIPTION> " + searchOutputData.versionString + " </DESCRIPTION>\n" );
      for ( int i = 0; i < tables.length; i++ )
      {
         VOSerializer.makeSerializer( DataFormat.TABLEDATA, tables[ i ] ).writeInlineTableElement( out );
      }
      out.write( "</RESOURCE>\n" );
      out.write( "</VOTABLE>\n" );
      out.flush();
   }

   private static StarTable makeSearchResultsTable(Subsurvey[] ssurv)
   {
      ColumnInfo[] colInfos = new ColumnInfo[ 6 + 2*4 ];

      int ix=0;

      colInfos[ ix++ ] = new ColumnInfo( "overlap",     Integer.class, "Overlap Code" );
      colInfos[ ix++ ] = new ColumnInfo( "overlapSky",  Integer.class, "Overlap Code for Sky axes" );
      colInfos[ ix++ ] = new ColumnInfo( "overlapSpec", Integer.class, "Overlap Code for Spectral axis" );

      colInfos[ ix++ ] = new ColumnInfo( "dataType",    String.class,  "Data Type (image|cube)" );
      colInfos[ ix++ ] = new ColumnInfo( "pubdid",      String.class,  "PublisherDid" );
      colInfos[ ix++ ] = new ColumnInfo( "access_url",  String.class,  "Access URL" );

      colInfos[ ix++ ] = new ColumnInfo( "P1lon", Double.class, "longitude" );
      colInfos[ ix++ ] = new ColumnInfo( "P1lat", Double.class, "latitude" );
      colInfos[ ix++ ] = new ColumnInfo( "P2lon", Double.class, "longitude" );
      colInfos[ ix++ ] = new ColumnInfo( "P2lat", Double.class, "latitude" );
      colInfos[ ix++ ] = new ColumnInfo( "P3lon", Double.class, "longitude" );
      colInfos[ ix++ ] = new ColumnInfo( "P3lat", Double.class, "latitude" );
      colInfos[ ix++ ] = new ColumnInfo( "P4lon", Double.class, "longitude" );
      colInfos[ ix++ ] = new ColumnInfo( "P4lat", Double.class, "latitude" );

      RowListStarTable astro = new RowListStarTable( colInfos );

      for(Subsurvey subsurvey : ssurv)
      {
         for(Dataset dataset : subsurvey.datasetArr)
         {
            astro.addRow( new Object[] 
                  {
                     new Integer( dataset.overlapCode ),
                     new Integer( dataset.overlapCodeSky ),
                     new Integer( dataset.overlapCodeVel ),

                     dataset.dataType, 
                     dataset.publisherDid,
                     dataset.access.accessCutoutUrl,

                     new Double(dataset.vertices_deg.lon[0]), new Double(dataset.vertices_deg.lat[0]),
                     new Double(dataset.vertices_deg.lon[1]), new Double(dataset.vertices_deg.lat[1]),
                     new Double(dataset.vertices_deg.lon[2]), new Double(dataset.vertices_deg.lat[2]),
                     new Double(dataset.vertices_deg.lon[3]), new Double(dataset.vertices_deg.lat[3]),
                  });
         }
      }

      return astro;
   }

   // legacy

   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();
   }


}
