/*
  This file is part of CDO. CDO is a collection of Operators to
  manipulate and analyse Climate model Data.

  Copyright (C) 2003-2020 Uwe Schulzweida, <uwe.schulzweida AT mpimet.mpg.de>
  See COPYING file for copying and redistribution conditions.

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; version 2 of the License.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.
*/

#include <cdi.h>

#include "cdo_options.h"
#include "cdo_vlist.h"
#include "cdo_cdi_wrapper.h"
#include "param_conversion.h"
#include "process_int.h"
#include "timer.h"
#include "util_files.h"


static void
print_stat(const char *sinfo, MemType memtype, int datatype, int filetype, off_t nvalues, double data_size, double file_size, double tw)
{
  nvalues /= 1000000;
  data_size /= 1024. * 1024. * 1024.;

  cdoPrint("%s Read %.1f GB of %d bit floats from %s %s, %.1f MVal/s", sinfo, data_size, memtype == MemType::Float ? 32 : 64,
           cdi_datatype2str(datatype), cdi_filetype2str(filetype), tw > 0 ? nvalues / tw : -1);

  file_size /= 1024. * 1024. * 1024.;
  cdoPrint("%s Read %.1f GB in %.1f seconds, total %.1f MB/s", sinfo, file_size, tw, tw > 0 ? 1024 * file_size / tw : -1);
}

void *
CDIread(void *process)
{
  const auto memtype = Options::CDO_Memtype;
  int varID, levelID;
  size_t nmiss;
  int nrecs;
  int filetype = -1, datatype = -1;
  char sinfo[64];
  off_t nvalues = 0;
  double file_size = 0, data_size = 0;
  double twsum = 0;

  sinfo[0] = 0;

  cdoInitialize(process);

  if (Options::cdoVerbose) cdoPrint("parameter: <nruns>");

  if (operatorArgc() > 1) cdoAbort("Too many arguments!");

  auto nruns = (operatorArgc() == 1) ? parameter2int(cdoOperatorArgv(0)) : 1;
  if (nruns < 0) nruns = 0;
  if (nruns > 99) nruns = 99;

  if (Options::cdoVerbose) cdoPrint("nruns      : %d", nruns);

  // vlistDefNtsteps(vlistID, 1);

  for (int irun = 0; irun < nruns; ++irun)
    {
      const auto tw0 = timer_val(timer_read);
      data_size = 0;
      nvalues = 0;

      const auto streamID = cdoOpenRead(0);
      const auto vlistID = cdoStreamInqVlist(streamID);

      VarList varList;
      varListInit(varList, vlistID);

      filetype = cdoInqFiletype(streamID);
      datatype = vlistInqVarDatatype(vlistID, 0);

      const auto gridsizemax = vlistGridsizeMax(vlistID);

      Varray<float> farray;
      Varray<double> darray;
      if (memtype == MemType::Float)
        farray.resize(gridsizemax);
      else
        darray.resize(gridsizemax);

      auto t0 = timer_val(timer_read);

      int tsID = 0;
      while ((nrecs = cdoStreamInqTimestep(streamID, tsID)))
        {

          for (int recID = 0; recID < nrecs; recID++)
            {
              cdoInqRecord(streamID, &varID, &levelID);

              const auto gridsize = varList[varID].gridsize;
              nvalues += gridsize;

              if (memtype == MemType::Float)
                {
                  cdoReadRecordF(streamID, farray.data(), &nmiss);
                  data_size += gridsize * 4;
                }
              else
                {
                  cdoReadRecord(streamID, darray.data(), &nmiss);
                  data_size += gridsize * 8;
                }
            }

          if (Options::cdoVerbose)
            {
              const auto tw = timer_val(timer_read) - t0;
              t0 = timer_val(timer_read);
              cdoPrint("Timestep %d: %.2f seconds", tsID + 1, tw);
            }

          tsID++;
        }

      cdoStreamClose(streamID);

      const auto tw = timer_val(timer_read) - tw0;
      twsum += tw;

      file_size = (double) fileSize(cdoGetStreamName(0));

      if (nruns > 1) snprintf(sinfo, sizeof(sinfo), "(run %d)", irun + 1);

      print_stat(sinfo, memtype, datatype, filetype, nvalues, data_size, file_size, tw);
    }

  if (nruns > 1) print_stat("(mean)", memtype, datatype, filetype, nvalues, data_size, file_size, twsum / nruns);

  cdoFinish();

  return nullptr;
}
