import java.util.logging.Logger;
import java.util.List;
import java.util.ArrayList;

class SearchOutputData
{
   private static final Logger LOGGER = Logger.getLogger("SearchOutputData");

   String description;
   int datacubeCount;
   String versionString;
   Subsurvey[] subsurveyArr;


   public static SearchOutputData  marshall(Dataset[] datasetArr,
         SubsurveyId subsurveyId, Subsurvey[] dbSubsurveys,
         String mergeUrlRoot, String mergeQueryString)
   {
      SearchOutputData sod = new SearchOutputData();

      sod.description = "Via Lactea Knowledge Base response (Search by pgSphere)";
      sod.versionString = "Search (pgSphere) version " + Version.asString;
      sod.datacubeCount = datasetArr.length;

      sod.subsurveyArr = groupBySubsurveys(datasetArr, subsurveyId, dbSubsurveys, mergeUrlRoot, mergeQueryString);
      return sod;
   }

   // assumes datasetArr is already ordered by subsurveys
   private static Subsurvey[] groupBySubsurveys(Dataset[] datasetArr,
         SubsurveyId subsurveyId, Subsurvey[] dbSubsurveys,
         String mergeUrlRoot, String mergeQueryString)
   {
      List<Subsurvey> subsurveyList = new ArrayList<Subsurvey>();

      if(datasetArr.length > 0)
      {
         List<Dataset> datasetList  = new ArrayList<Dataset>();
         String prevSubsurveyId = datasetArr[0].subsurvey_id;

         for(Dataset dataset : datasetArr)
         {

            if( ! prevSubsurveyId.equals(dataset.subsurvey_id) )
            {
               if( false )//Dataset.areDatasetsMergeable(datasetList) )
               {
                  Dataset mergedDataset = new Dataset(datasetList, subsurveyId, mergeUrlRoot, mergeQueryString);
                  datasetList.add(mergedDataset);
               }

               Subsurvey subsurvey = new Subsurvey(Subsurvey.findSubsurvey(dbSubsurveys, prevSubsurveyId));

               subsurvey.datasetArr = datasetList.toArray(new Dataset[0]);
               subsurveyList.add(subsurvey);

               datasetList.clear();
            }

            datasetList.add( dataset );

            prevSubsurveyId = dataset.subsurvey_id;
         }

         if( false )//Dataset.areDatasetsMergeable(datasetList) )
         {
            Dataset mergedDataset = new Dataset(datasetList, subsurveyId, mergeUrlRoot, mergeQueryString);
            datasetList.add(mergedDataset);
         }

         Subsurvey subsurvey = new Subsurvey(Subsurvey.findSubsurvey(dbSubsurveys, prevSubsurveyId));

         subsurvey.datasetArr = datasetList.toArray(new Dataset[0]);
         subsurveyList.add(subsurvey);

         datasetList.clear();
      }

      return subsurveyList.toArray(new Subsurvey[0]);
   }

}

