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;
   AuthPolicy auth;
   Coord coord;
   SubsurveyId subsurveyId;
   boolean countNullValues;
   int datacubeCount;
   String versionString;
   Subsurvey[] subsurveyArr;


   public static SearchOutputData  marshall(Dataset[] datasetArr, AuthPolicy auth, Coord coord, SubsurveyId subsurveyId, boolean countNullValues, String mergeUrlRoot, Subsurvey[] dbSubsurveys)
   {
      SearchOutputData sod = new SearchOutputData();

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

      sod.subsurveyArr = groupBySubsurveys(datasetArr, auth, coord, subsurveyId, countNullValues, dbSubsurveys, mergeUrlRoot);
      return sod;
   }

   private static Subsurvey[] groupBySubsurveys(Dataset[] datasetArr, AuthPolicy auth, Coord coord, SubsurveyId subsurveyId, boolean countNullValues, 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, auth, coord, subsurveyId, countNullValues, 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, auth, coord, subsurveyId, countNullValues, 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]);
   }

}

