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

      Selvar     selparam        Select parameters by identifier (format: code.tabnum  or  pnum.cat.dis)
      Selvar     delparam        Delete parameters by identifier (format: code.tabnum  or  pnum.cat.dis)
      Selvar     selcode         Select parameters by code number
      Selvar     delcode         Delete parameters by code number
      Selvar     selname         Select parameters by name
      Selvar     delname         Delete parameters by name
      Selvar     selstdname      Select parameters by CF standard name
      Selvar     sellevel        Select levels
      Selvar     sellevidx       Select levels by index
      Selvar     selgrid         Select grids
      Selvar     selzaxis        Select zaxis
      Selvar     seltabnum       Select parameter table number
      Selvar     selltype        Select GRIB level type
*/

#include <cdi.h>

#include "cdo_options.h"
#include "process_int.h"
#include "cdo_vlist.h"
#include "cdo_zaxis.h"
#include "util_wildcards.h"
#include "cdi_lockedIO.h"
#include "param_conversion.h"

void *
Selvar(void *process)
{
  int varID2, levelID2;
  int varID, levelID;
  int nsel = 0;
  char paramstr[32];
  char varname[CDI_MAX_NAME];
  char stdname[CDI_MAX_NAME];
  char gridname[CDI_MAX_NAME];
  char zaxistypename[CDI_MAX_NAME];
  char zaxisname[CDI_MAX_NAME];
  size_t nmiss;
  std::vector<int> intarr;
  std::vector<double> fltarr;

  cdoInitialize(process);

  const auto lcopy = unchangedRecord();

#define INVERTS_SELECTION(id) (cdoOperatorF2(id) & 1)
#define TAKES_STRINGS(id) (cdoOperatorF2(id) & 2)
#define TAKES_INTEGERS(id) (cdoOperatorF2(id) & 4)
#define TAKES_FLOATS(id) (cdoOperatorF2(id) & 8)

  // clang-format off
  const auto SELPARAM     = cdoOperatorAdd("selparam",     0, 2,   "parameters");
  const auto SELCODE      = cdoOperatorAdd("selcode",      0, 4,   "code numbers");
  const auto SELNAME      = cdoOperatorAdd("selname",      0, 2,   "variable names");
  const auto SELSTDNAME   = cdoOperatorAdd("selstdname",   0, 2,   "standard names");
  const auto SELLEVEL     = cdoOperatorAdd("sellevel",     0, 8,   "levels");
  const auto SELLEVIDX    = cdoOperatorAdd("sellevidx",    0, 4,   "index of levels");
  const auto SELGRID      = cdoOperatorAdd("selgrid",      0, 4|2, "list of grid names or numbers");
  const auto SELZAXIS     = cdoOperatorAdd("selzaxis",     0, 4|2, "list of zaxis types or numbers");
  const auto SELZAXISNAME = cdoOperatorAdd("selzaxisname", 0, 2,   "list of zaxis names");
  const auto SELTABNUM    = cdoOperatorAdd("seltabnum",    0, 4,   "table numbers");
  const auto DELPARAM     = cdoOperatorAdd("delparam",     1, 2|1, "parameter");
  const auto DELCODE      = cdoOperatorAdd("delcode",      1, 1,   "code numbers");
  const auto DELNAME      = cdoOperatorAdd("delname",      1, 2|1, "variable names");
  const auto SELLTYPE     = cdoOperatorAdd("selltype",     0, 4,   "GRIB level types");
  // clang-format on

  const auto operatorID = cdoOperatorID();

  operatorInputArg(cdoOperatorEnter(operatorID));

  const bool ldelete = (cdoOperatorF1(operatorID) == 1);

  int args_are_numeric = operatorArgc() > 0 && isdigit(cdoOperatorArgv(0)[0]);

  auto argnames = cdoGetOperArgv();
  if (TAKES_STRINGS(operatorID) && !(TAKES_INTEGERS(operatorID) && args_are_numeric))
    {
      nsel = operatorArgc();

      if (Options::cdoVerbose)
        for (int i = 0; i < nsel; i++) cdoPrint("name %d = %s", i + 1, argnames[i]);
    }
  else if (TAKES_FLOATS(operatorID))
    {
      fltarr = cdoArgvToFlt(argnames);
      nsel = fltarr.size();

      if (Options::cdoVerbose)
        for (int i = 0; i < nsel; i++) cdoPrint("flt %d = %g", i + 1, fltarr[i]);
    }
  else
    {
      intarr = cdoArgvToInt(argnames);
      nsel = intarr.size();

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

  std::vector<bool> selfound;
  if (nsel)
    {
      selfound.resize(nsel);
      for (int i = 0; i < nsel; i++) selfound[i] = false;
    }

  const auto streamID1 = cdoOpenRead(0);

  const auto vlistID1 = cdoStreamInqVlist(streamID1);
  auto nvars = vlistNvars(vlistID1);
  std::vector<bool> vars(nvars);

  if (operatorID == SELGRID && !args_are_numeric && nsel == 1 && argnames[0].compare(0, 4, "var=") == 0)
    {
      int gridnum = 0;
      const char *gridvarname = &argnames[0][4];
      if (*gridvarname == 0) cdoAbort("Variable name missing!");

      for (varID = 0; varID < nvars; varID++)
        {
          vlistInqVarName(vlistID1, varID, varname);
          if (strcmp(varname, gridvarname) == 0)
            {
              const auto gridID = vlistInqVarGrid(vlistID1, varID);
              gridnum = 1 + vlistGridIndex(vlistID1, gridID);
              args_are_numeric = true;
              intarr.push_back(gridnum);
              break;
            }
        }

      if (!gridnum) cdoAbort("Variable %s not found!", gridvarname);
    }

  vlistClearFlag(vlistID1);
  for (varID = 0; varID < nvars; varID++)
    {
      vars[varID] = ldelete;

      vlistInqVarName(vlistID1, varID, varname);
      int length = CDI_MAX_NAME;
      cdiInqKeyString(vlistID1, varID, CDI_KEY_STDNAME, stdname, &length);
      const auto param = vlistInqVarParam(vlistID1, varID);
      const auto code = vlistInqVarCode(vlistID1, varID);
      const auto tabnum = tableInqNum(vlistInqVarTable(vlistID1, varID));
      const auto gridID = vlistInqVarGrid(vlistID1, varID);
      const auto grididx = vlistGridIndex(vlistID1, gridID);
      const auto zaxisID = vlistInqVarZaxis(vlistID1, varID);
      const auto zaxisidx = vlistZaxisIndex(vlistID1, zaxisID);
      const auto nlevs = zaxisInqSize(zaxisID);
      gridName(gridInqType(gridID), gridname);
      length = CDI_MAX_NAME;
      cdiInqKeyString(zaxisID, CDI_GLOBAL, CDI_KEY_NAME, zaxisname, &length);
      zaxisName(zaxisInqType(zaxisID), zaxistypename);

      cdiParamToString(param, paramstr, sizeof(paramstr));

      for (int levID = 0; levID < nlevs; levID++)
        {
          const auto level = cdoZaxisInqLevel(zaxisID, levID);

          if (ldelete) vlistDefFlag(vlistID1, varID, levID, true);

          for (int isel = 0; isel < nsel; isel++)
            {
              bool found = false;
              if (operatorID == SELCODE)
                found = intarr[isel] == code;
              else if (operatorID == SELPARAM)
                found = wildcardmatch(argnames[isel], paramstr) == 0;
              else if (operatorID == SELNAME)
                found = wildcardmatch(argnames[isel], varname) == 0;
              else if (operatorID == SELSTDNAME)
                found = wildcardmatch(argnames[isel], stdname) == 0;
              else if (operatorID == SELLEVEL)
                found = std::fabs(fltarr[isel] - level) < 0.0001;
              else if (operatorID == SELLEVIDX)
                found = intarr[isel] == (levID + 1);
              else if (operatorID == SELGRID && args_are_numeric)
                found = intarr[isel] == (grididx + 1);
              else if (operatorID == SELGRID && !args_are_numeric)
                found = memcmp(argnames[isel].c_str(), gridname, argnames[isel].size()) == 0;
              else if (operatorID == SELZAXIS && args_are_numeric)
                found = intarr[isel] == (zaxisidx + 1);
              else if (operatorID == SELZAXIS && !args_are_numeric)
                found = memcmp(argnames[isel].c_str(), zaxistypename, argnames[isel].size()) == 0;
              else if (operatorID == SELZAXISNAME)
                found = wildcardmatch(argnames[isel], zaxisname) == 0;
              else if (operatorID == SELTABNUM)
                found = intarr[isel] == tabnum;
              else if (operatorID == DELCODE)
                found = intarr[isel] == code;
              else if (operatorID == DELNAME)
                found = wildcardmatch(argnames[isel], varname) == 0;
              else if (operatorID == DELPARAM)
                found = strcmp(argnames[isel].c_str(), paramstr) == 0;
              else if (operatorID == SELLTYPE)
                found = intarr[isel] == zaxis2ltype(zaxisID);

              if (found)
                {
                  vlistDefFlag(vlistID1, varID, levID, !INVERTS_SELECTION(operatorID));
                  selfound[isel] = true;
                  vars[varID] = !ldelete;
                }
            }
        }
    }

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

  for (varID = 0; varID < nvars; varID++)
    {
      if (vars[varID])
        {
          const auto zaxisID = vlistInqVarZaxis(vlistID1, varID);
          if (zaxisInqType(zaxisID) == ZAXIS_HYBRID)
            {
              const auto psvarid = vlist_get_psvarid(vlistID1, zaxisID);
              if (psvarid != -1 && !vars[psvarid])
                {
                  vars[psvarid] = true;
                  vlistDefFlag(vlistID1, psvarid, 0, !INVERTS_SELECTION(operatorID));
                }
            }
        }
    }

  for (int isel = 0; isel < nsel; isel++)
    {
      if (selfound[isel] == false)
        {
          if (operatorID == SELCODE || operatorID == DELCODE)
            cdoWarning("Code number %d not found!", intarr[isel]);
          else if (operatorID == SELPARAM || operatorID == DELPARAM)
            cdoWarning("Parameter %s not found!", argnames[isel]);
          else if (operatorID == SELNAME || operatorID == DELNAME)
            cdoWarning("Variable name %s not found!", argnames[isel]);
          else if (operatorID == SELSTDNAME)
            cdoWarning("Variable with standard name %s not found!", argnames[isel]);
          else if (operatorID == SELLEVEL)
            cdoWarning("Level %g not found!", fltarr[isel]);
          else if (operatorID == SELLEVIDX)
            cdoWarning("Level index %d not found!", intarr[isel]);
          else if (operatorID == SELGRID && args_are_numeric)
            cdoWarning("Grid %d not found!", intarr[isel]);
          else if (operatorID == SELGRID && !args_are_numeric)
            cdoWarning("Grid name %s not found!", argnames[isel]);
          else if (operatorID == SELZAXIS && args_are_numeric)
            cdoWarning("Zaxis %d not found!", intarr[isel]);
          else if (operatorID == SELZAXIS && !args_are_numeric)
            cdoWarning("Zaxis type %s not found!", argnames[isel]);
          else if (operatorID == SELZAXISNAME)
            cdoWarning("Zaxis name %s not found!", argnames[isel]);
          else if (operatorID == SELTABNUM)
            cdoWarning("Table number %d not found!", intarr[isel]);
          else if (operatorID == SELLTYPE)
            cdoWarning("GRIB level type %d not found!", intarr[isel]);
        }
    }

  if (npar == 0) cdoAbort("No variables selected!");

  const auto vlistID2 = vlistCreate();
  cdoVlistCopyFlag(vlistID2, vlistID1);

  if (Options::cdoVerbose) vlistPrint(vlistID2);

  nvars = vlistNvars(vlistID2);
  for (varID = 0; varID < nvars; ++varID)
    if (vlistInqVarTimetype(vlistID2, varID) != TIME_CONSTANT) break;
  if (varID == nvars) vlistDefNtsteps(vlistID2, 0);

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

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

  Varray<double> array;
  if (!lcopy)
    {
      auto gridsizemax = vlistGridsizeMax(vlistID1);
      if (vlistNumber(vlistID1) != CDI_REAL) gridsizemax *= 2;
      array.resize(gridsizemax);
    }

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

      for (int recID = 0; recID < nrecs; recID++)
        {
          cdoInqRecord(streamID1, &varID, &levelID);
          if (vlistInqFlag(vlistID1, varID, levelID) == true)
            {
              varID2 = vlistFindVar(vlistID2, varID);
              levelID2 = vlistFindLevel(vlistID2, varID, levelID);

              cdoDefRecord(streamID2, varID2, levelID2);
              if (lcopy)
                {
                  cdoCopyRecord(streamID2, streamID1);
                }
              else
                {
                  cdoReadRecord(streamID1, array.data(), &nmiss);
                  cdoWriteRecord(streamID2, array.data(), nmiss);
                }
            }
        }

      tsID++;
    }

  cdoStreamClose(streamID2);
  cdoStreamClose(streamID1);

  vlistDestroy(vlistID2);

  cdoFinish();

  return nullptr;
}
