/*
  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.
*/

/*
   This module contains the following operators:

      Selgridcell     selgridcell    Select grid cells by indices
*/

#include <cdi.h>

#include "cdo_options.h"
#include "process_int.h"
#include "cdo_cdi_wrapper.h"
#include <mpim_grid.h>
#include "gridreference.h"
#include "util_files.h"
#include "param_conversion.h"

int gengridcell(const int gridID1, const size_t gridsize2, const long *const cellidx);

static int
genindexgrid(int gridID1, const size_t gridsize2, const long *const cellidx)
{
  const auto gridID0 = gridID1;
  auto gridtype1 = gridInqType(gridID1);

  if (gridtype1 == GRID_LONLAT || gridtype1 == GRID_GAUSSIAN || gridtype1 == GRID_PROJECTION)
    {
      gridID1 = gridToCurvilinear(gridID1, 0);
      gridtype1 = GRID_CURVILINEAR;
    }
  else if (gridtype1 == GRID_UNSTRUCTURED && !gridHasCoordinates(gridID1))
    {
      const auto reference = dereferenceGrid(gridID1);
      if (reference.isValid) gridID1 = reference.gridID;
      if (reference.notFound) cdoWarning("Reference to source grid not found!");
    }

  int gridID2 = -1;
  if (gridtype1 == GRID_UNSTRUCTURED || gridtype1 == GRID_CURVILINEAR)
    gridID2 = gengridcell(gridID1, gridsize2, cellidx);
  else if (gridtype1 == GRID_GENERIC && gridInqYsize(gridID1) == 0)
    gridID2 = gengridcell(gridID1, gridsize2, cellidx);

  if (gridID0 != gridID1) gridDestroy(gridID1);

  return gridID2;
}

static void
selectIndex(double *array1, double *array2, long nind, long *indarr)
{
  for (long i = 0; i < nind; ++i) array2[i] = array1[indarr[i]];
}

void *
Selgridcell(void *process)
{
  int nrecs;
  int gridID1 = -1, gridID2;
  int index, gridtype = -1;
  struct sindex_t
  {
    int gridID1, gridID2;
  };
  std::vector<int> indarr;

  cdoInitialize(process);

  cdoOperatorAdd("selgridcell", 0, 0, "grid cell indices (1-N)");
  const auto DELGRIDCELL = cdoOperatorAdd("delgridcell", 0, 0, "grid cell indices (1-N)");

  operatorInputArg(cdoOperatorEnter(0));

  const auto operatorID = cdoOperatorID();

  if (operatorArgc() < 1) cdoAbort("Too few arguments!");

  int nind = 0;
  if (operatorArgc() == 1)
    {
      bool maskfile = true, indexfile = false;
      const char *filename = cdoOperatorArgv(0).c_str();
      if (strncmp(filename, "index=", 6) == 0)
        {
          filename += 6;
          indexfile = true;
        }
      else if (strncmp(filename, "mask=", 5) == 0)
        {
          filename += 5;
          maskfile = true;
        }

      if (fileExists(filename))
        {
          if (indexfile)
            {
              size_t cdo_read_index(const char *indexfile, std::vector<int> &indarr);
              const auto n = cdo_read_index(filename, indarr);
              nind = n;
              if (nind == 0) cdoAbort("Index file %s generates no input!", cdoOperatorArgv(0).c_str());
            }
          else if (maskfile)
            {
              size_t cdo_read_mask(const char *maskfile, std::vector<bool> &imask);
              std::vector<bool> mask;
              const auto n = cdo_read_mask(filename, mask);
              nind = 0;
              for (size_t i = 0; i < n; ++i)
                if (mask[i]) nind++;
              if (nind == 0) cdoAbort("Mask is empty!");

              indarr.resize(nind);
              nind = 0;
              for (size_t i = 0; i < n; ++i)
                if (mask[i]) indarr[nind++] = i;

              if (nind == 0) cdoAbort("Mask file %s generates no input!", cdoOperatorArgv(0).c_str());
            }
        }
    }

  if (nind == 0)
    {
      indarr = cdoArgvToInt(cdoGetOperArgv());
      nind = indarr.size();

      if (Options::cdoVerbose)
        for (int i = 0; i < nind; i++) cdoPrint("int %d = %d", i + 1, indarr[i]);

      for (int i = 0; i < nind; i++) indarr[i] -= 1;
    }

  if (nind == 0) cdoAbort("Argument %s generates no input!", cdoOperatorArgv(0).c_str());

  auto indmin = indarr[0];
  auto indmax = indarr[0];
  for (int i = 1; i < nind; i++)
    {
      if (indmax < indarr[i]) indmax = indarr[i];
      if (indmin > indarr[i]) indmin = indarr[i];
    }

  if (indmin < 0) cdoAbort("Index < 1 not allowed!");

  const auto streamID1 = cdoOpenRead(0);

  const auto vlistID1 = cdoStreamInqVlist(streamID1);
  const auto vlistID2 = vlistDuplicate(vlistID1);

  const auto taxisID1 = vlistInqTaxis(vlistID1);
  const auto taxisID2 = taxisDuplicate(taxisID1);
  vlistDefTaxis(vlistID2, taxisID2);

  const auto nvars = vlistNvars(vlistID1);
  std::vector<bool> vars(nvars);
  for (int varID = 0; varID < nvars; varID++) vars[varID] = false;

  const auto ngrids = vlistNgrids(vlistID1);
  std::vector<sindex_t> sindex(ngrids);

  long ncells = nind;
  std::vector<long> cellidx;
  if (operatorID == DELGRIDCELL)
    {
      const auto gridsize = vlistGridsizeMax(vlistID1);
      ncells = gridsize - nind;
      cellidx.resize(gridsize);
      for (size_t i = 0; i < gridsize; ++i) cellidx[i] = 1;
      for (long i = 0; i < nind; ++i) cellidx[indarr[i]] = 0;
      long j = 0;
      for (size_t i = 0; i < gridsize; ++i)
        if (cellidx[i] == 1) cellidx[j++] = i;
      if (j != ncells) cdoAbort("Internal error; number of cells differ");
    }
  else
    {
      cellidx.resize(nind);
      for (int i = 0; i < nind; ++i) cellidx[i] = indarr[i];
    }

  if (ncells == 0) cdoAbort("Mask is empty!");

  for (index = 0; index < ngrids; index++)
    {
      gridID1 = vlistGrid(vlistID1, index);
      gridtype = gridInqType(gridID1);

      const auto gridsize = gridInqSize(gridID1);
      if (gridsize == 1) continue;
      if (indmax >= (int) gridsize)
        {
          cdoWarning("Max grid index is greater than grid size, skipped grid %d!", index + 1);
          continue;
        }

      gridID2 = genindexgrid(gridID1, ncells, cellidx.data());

      if (gridID2 == -1)
        {
          cdoWarning("Unsupported grid type >%s<, skipped grid %d!", gridNamePtr(gridtype), index + 1);
          continue;
        }

      sindex[index].gridID1 = gridID1;
      sindex[index].gridID2 = gridID2;

      vlistChangeGridIndex(vlistID2, index, gridID2);

      for (int varID = 0; varID < nvars; varID++)
        if (gridID1 == vlistInqVarGrid(vlistID1, varID)) vars[varID] = true;
    }

  {
    int varID;
    for (varID = 0; varID < nvars; varID++)
      if (vars[varID]) break;

    if (varID >= nvars) cdoAbort("No variables selected!");
  }

  const auto streamID2 = cdoOpenWrite(1);
  cdoDefVlist(streamID2, vlistID2);

  auto gridsize = vlistGridsizeMax(vlistID1);
  if (vlistNumber(vlistID1) != CDI_REAL) gridsize *= 2;
  Varray<double> array1(gridsize);

  auto gridsizemax = vlistGridsizeMax(vlistID2);
  if (vlistNumber(vlistID2) != CDI_REAL) gridsizemax *= 2;
  Varray<double> array2(gridsizemax);

  int tsID = 0;
  while ((nrecs = cdoStreamInqTimestep(streamID1, tsID)))
    {
      taxisCopyTimestep(taxisID2, taxisID1);
      cdoDefTimestep(streamID2, tsID);

      for (int recID = 0; recID < nrecs; recID++)
        {
          size_t nmiss;
          int varID, levelID;
          cdoInqRecord(streamID1, &varID, &levelID);
          cdoReadRecord(streamID1, array1.data(), &nmiss);

          cdoDefRecord(streamID2, varID, levelID);

          if (vars[varID])
            {
              gridID1 = vlistInqVarGrid(vlistID1, varID);

              for (index = 0; index < ngrids; index++)
                if (gridID1 == sindex[index].gridID1) break;

              if (index == ngrids) cdoAbort("Internal problem, grid not found!");

              const auto gridsize2 = gridInqSize(sindex[index].gridID2);

              selectIndex(array1.data(), array2.data(), ncells, cellidx.data());

              if (nmiss)
                {
                  const auto missval = vlistInqVarMissval(vlistID2, varID);
                  nmiss = varrayNumMV(gridsize2, array2, missval);
                }

              cdoWriteRecord(streamID2, array2.data(), nmiss);
            }
          else
            {
              cdoWriteRecord(streamID2, array1.data(), nmiss);
            }
        }

      tsID++;
    }

  cdoStreamClose(streamID2);
  cdoStreamClose(streamID1);

  vlistDestroy(vlistID2);

  cdoFinish();

  return nullptr;
}
