
//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)
   {
      // FIXME make static final
      ColumnInfo[] colInfos =
      {
         new ColumnInfo( "dataproduct_type",  String.class,  "Dataproduct Type (image|cube)" ),
         new ColumnInfo( "calib_level",       Integer.class, "Calibration level" ),
         new ColumnInfo( "obs_collection",    String.class,  "Collection" ),
         new ColumnInfo( "obs_id",            String.class,  "Observation Id" ),
         new ColumnInfo( "obs_publisher_did", String.class,  "Publisher Did" ),

         new ColumnInfo( "access_url",     String.class, "Access URL" ),
         new ColumnInfo( "access_format",  String.class, "Format (MIME type)" ),
         new ColumnInfo( "access_estsize", Long.class,   "Extimated size (KB)" ),

         new ColumnInfo( "target_name", String.class,  "Target" ),

         new ColumnInfo( "s_ra",         Double.class, "Right Ascention" ),
         new ColumnInfo( "s_dec",        Double.class, "Declination" ),
         new ColumnInfo( "s_fov",        Double.class, "Field of view" ),
         new ColumnInfo( "s_region",     String.class, "Region" ),
         new ColumnInfo( "s_xel1",       Long.class,   "Pixels axis1" ),
         new ColumnInfo( "s_xel2",       Long.class,   "Pixels axis2" ),
         new ColumnInfo( "s_resolution", Double.class, "Spatial resolution" ),

         new ColumnInfo( "t_min",        Double.class, "Time min" ),
         new ColumnInfo( "t_max",        Double.class, "Time max" ),
         new ColumnInfo( "t_exptime",    Double.class, "Exposure time" ),
         new ColumnInfo( "t_resolution", Double.class, "Time resolution" ),
         new ColumnInfo( "t_xel",        Long.class,   "Time pixels" ),

         new ColumnInfo( "em_min",       Double.class, "Spectrum min" ),
         new ColumnInfo( "em_max",       Double.class, "Spectrum max" ),
         new ColumnInfo( "em_res_power", Double.class, "Spectrum resolution power" ),
         new ColumnInfo( "em_xel",       Long.class,   "Spectrum pixels" ),

         new ColumnInfo( "o_ucd", String.class, "Observable UCD" ),

         new ColumnInfo( "pol_states", String.class, "Polarization states" ),
         new ColumnInfo( "pol_xel",    Long.class,   "Polarization pixels" ),

         new ColumnInfo( "facility_name", String.class, "Facility" ),
         new ColumnInfo( "instrument_name", String.class, "Instrument" ),


         // VLKB extensions
         new ColumnInfo( "overlap",     Integer.class, "Overlap Code" ),
         new ColumnInfo( "overlapSky",  Integer.class, "Overlap Code for Sky axes" ),
         new ColumnInfo( "overlapSpec", Integer.class, "Overlap Code for Spectral axis" ),

         new ColumnInfo( "P1lon", Double.class, "P1 longitude" ),
         new ColumnInfo( "P1lat", Double.class, "P1 latitude" ),
         new ColumnInfo( "P2lon", Double.class, "P2 longitude" ),
         new ColumnInfo( "P2lat", Double.class, "P2 latitude" ),
         new ColumnInfo( "P3lon", Double.class, "P3 longitude" ),
         new ColumnInfo( "P3lat", Double.class, "P3 latitude" ),
         new ColumnInfo( "P4lon", Double.class, "P4 longitude" ),
         new ColumnInfo( "P4lat", Double.class, "P4 latitude" )
      };

      RowListStarTable astro = new RowListStarTable( colInfos );

      for(Subsurvey subsurvey : ssurv)
      {
         for(Dataset dataset : subsurvey.datasetArr)
         {
            if(dataset.obsDataset == null) continue; // skip mergeable datasets

            astro.addRow( new Object[] 
                  {
                     // ObsCore
                     dataset.obsDataset.dataproduct_type,//dataset.dataType, 
                        new Integer( dataset.obsDataset.calib_level ),
                        dataset.obsDataset.obs_collection,
                        dataset.obsDataset.obs_id,
                        dataset.obsDataset.obs_publisher_did,

                        dataset.obsDataset.access_url,//dataset.access.accessCutoutUrl,
                        dataset.obsDataset.access_format,
                        new Long( dataset.obsDataset.access_estsize ),

                        dataset.obsDataset.target_name,

                        new Double(dataset.obsDataset.s_ra),new Double(dataset.obsDataset.s_dec),new Double(dataset.obsDataset.s_fov),
                        dataset.obsDataset.s_region,
                        new Long( dataset.obsDataset.s_xel1 ), new Long( dataset.obsDataset.s_xel2 ),
                        new Double(dataset.obsDataset.s_resolution),

                        new Double(dataset.obsDataset.t_min), new Double(dataset.obsDataset.t_max),
                        new Double(dataset.obsDataset.t_exptime), new Double(dataset.obsDataset.t_resolution),
                        new Long( dataset.obsDataset.t_xel ),

                        new Double(dataset.obsDataset.em_min), new Double(dataset.obsDataset.em_max),
                        new Double(dataset.obsDataset.em_res_power),
                        new Long( dataset.obsDataset.em_xel ),

                        dataset.obsDataset.o_ucd,

                        dataset.obsDataset.pol_states,
                        new Long( dataset.obsDataset.pol_xel ),

                        dataset.obsDataset.facility_name,
                        dataset.obsDataset.instrument_name,


                        // VLKB extensions
                        new Integer( dataset.overlapCode ),
                        new Integer( dataset.overlapCodeSky ),
                        new Integer( dataset.overlapCodeVel ),

                        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>");

      writer.println("<inputs>");
      if(searchOutputData.subsurveyId != null) writer.println(serialize(searchOutputData.subsurveyId));
      if(searchOutputData.coord       != null) writer.println(serialize(searchOutputData.coord));
      if(searchOutputData.countNullValues)     writer.println("<nullvals> set </nullvals>");
      if(searchOutputData.auth        != null) writer.println(serialize(searchOutputData.auth));
      writer.println("</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, 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();
   }


}
