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;
   Inputs inputs;
   int datacubeCount;
   String versionString;
   Subsurvey[] subsurveyArr;


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

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

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

   private static Subsurvey[] groupBySubsurveys(Dataset[] datasetArr, Inputs inputs, Subsurvey[] dbSubsurveys, String mergeUrlRoot)
   {
      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( Dataset.areDatasetsMergeable(datasetList) )
               {
                  Dataset mergedDataset = new Dataset(datasetList, inputs, mergeUrlRoot);
                  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( Dataset.areDatasetsMergeable(datasetList) )
         {
            Dataset mergedDataset = new Dataset(datasetList, inputs, mergeUrlRoot);
            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]);
   }

}

