
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;

import java.util.List;
import java.util.ArrayList;

import vo.parameter.*;

final class XmlSerializer
{
   private XmlSerializer() {}

   // VOTable

   public static void serializeToVoTable(
         PrintWriter writer, String charEncoding,
         Dataset[] datasetArr,
         String cutoutUrl, String mergeUrl,
         boolean showDuration, long startTime_msec) throws IOException
   {
      StarTable dstable = makeSearchResultsTable( datasetArr );

      dstable.setParameter(new DescribedValue(
               new DefaultValueInfo("datacubeCount", Integer.class, "Count of all datacubes from VLKB-search" ),
               datasetArr.length ) );

      BufferedWriter out = new BufferedWriter( writer );

      out.write("<?xml-stylesheet type='text/xsl' href='VOTable2XHTML.xsl'?>");
      out.write( "<VOTABLE version='1.1'>" );
      out.write( "<RESOURCE type=\"results\">" );
      out.write( "<DESCRIPTION> " + Version.asString + " </DESCRIPTION>" );

      VOSerializer.makeSerializer( DataFormat.TABLEDATA, dstable ).writeInlineTableElement( out );

      out.write( "</RESOURCE>" );

      out.write( "<RESOURCE type=\"meta\" utype=\"adhoc:service\" name=\"CutoutService\" >" );
      out.write( "<DESCRIPTION> VLKB cutout service </DESCRIPTION>");
      out.write( "<PARAM name=\"standardID\" datatype=\"char\" arraysize=\"*\" value=\"ivo://ivoa.net/std/SODA#sync-1.0\" />");
      out.write( "<PARAM name=\"accessURL\" datatype=\"char\" arraysize=\"*\" value=\"" + cutoutUrl +  "\" />");
      out.write( "<GROUP name=\"inputParams\">");
      out.write( "<PARAM name=\"ID\" datatype=\"char\" arraysize=\"*\" value=\"\" ref=\"primaryID\" />"); // FIXME results table obs_publisher_did FIELD must have attrib: ID="primaryID"
      out.write( "</GROUP>");
      out.write( "</RESOURCE>" );

      out.write( "</VOTABLE>" );
      out.flush();
   }

   private static StarTable makeSearchResultsTable(Dataset[] datasetArr)
   {
      RowListStarTable astro = new RowListStarTable( ObscoreExt.OBSCORE_VLKB_COLINFO );

      for(Dataset dataset : datasetArr)
      {
         if(dataset.obsCore == null) continue; // FIXME skip mergeable datasets

         astro.addRow( ObscoreExt.obscoreVlkbRow(dataset) );
      }

      return astro;
   }


}
